当前位置: 首页 > 后端技术 > Node.js

你可能不知道的一些有用的JS技巧

时间:2023-04-03 16:37:29 Node.js

最近看完了JavaScriptEnlightenment。本书偏重于JavaScript的基础知识,适合初学者。以下是我从本书中获得的好处和扩展的列表。MathJavaScript开发人员经常将构造函数名称大写以将构造函数与普通函数区分开来。因此,一些开发人员可能会将Math误认为是函数,因为名称是大写的,而Math实际上只是一个object.console.log(typeofMath);//objectconsole.log(typeofArray);//functionFunction构造函数有两种方式:函数声明/表达式functionsum(x,y){returnx+y;}console.log(sum(3,4));//7Functionconstructorletmultiply=newFunction("x","y","returnx*y;");console.log(multiply(3,4));//12在开发中,我们经常需要使用call或者apply来切换函数上下文。例如函数print(){console.log(this.a);}print.call({a:'hello'});//hello有些面试题会问whyprintdoes没有将call定义为其属性,但print.call()不会抛出错误。这是因为print是Functionconstructor的一个实例,所以它通过原型chain.print.call===Function.prototype.call继承了Function.prototype中定义的所有方法如何做Arraychecktypeof可以用来确定原始数据类型的类型。但它无法区分数组和对象。console.log(typeof[1,2]);//objectconsole.log(typeof{});//objectThereareseveralwasytodoArraycheck:API:Array.isArrayconsole.log(Array.isArray([1,2]));//truetoStringconsole.log(Object.prototype.toString.call([1,2]).toLowerCase()==='[对象数组]');//trueNote在这里我们必须使用Object.prototype.toStringwithcall来切换调用上下文,因为Array.prototype.toString是overriden.console.log(Object.prototype.toString.call([1,2]));//[对象数组]console.log([1,2].toString());//1,2instanceof[1,2]instanceofArray===true;Object.prototype.toString不适用于自定义数据类型。在这种情况下,我们可以使用instanceof来确定type.classPerson{}letmike=newPerson();console.log(Object.prototype.toString.call(mike));//[objectObject]console.log(mikeinstanceofPerson);//trueundefinedvsnullundefined-没有值变量未定义有两种情况。变量已定义但未分配任何值。lets;console.log(s);//undefined变量根本没有定义.letobj1={};console.log(obj1.a);//undefinednull-特殊值obj2={a:null};console.log(obj2.a);//null如果我们的目标是过滤掉undefined和null,我们可以使用双等号弱比较(即==).console.log(null==undefined);//trueletarr=[null,undefined,1];letfil=arr.filter(it=>{returnit!=null;});console.log(fil);//[1]参考JavaScriptEnlightenmentNotice如果你从这个Repo中受益,请「Star」支持。如果你想关注系列读书笔记的最新消息/文章,请「收看」订阅。