Loading... > # **一.运算相关** ``` console.log('10.567890'|0); //10 console.log('10.567890'^0); //10 console.log(-2.23456789|0); //-2 console.log(~~-2.23456789); //-2 ``` > # **二.首次为变量赋值时务必使用var关键字** 变量没有声明而直接赋值得话,默认会作为一个新的全局变量,要尽量避免使用全局变量。 > # 三.使用===取代== ==和!=操作符会在需要的情况下自动转换数据类型。但===和!==不会,它们会同时比较值和数据类型,这也使得它们要比==和!=快。 ``` [10] === 10 // is false [10] == 10 // is true '10' == 10 // is true '10' === 10 // is false [] == 0 // is true [] === 0 // is false '' == false // is true '' === false // is false ``` > # 四.js对象转换: ```js //1.日期转数值: var d = +new Date(); //1295698416792 //2. 类数组对象转数组: var arr = [].slice.call(arguments) ``` > # 五.漂亮的随机码 ```js Math.random().toString(16).substring(2); //14位 Math.random().toString(36).substring(2); //11位 ``` > # 六.合并数组: ```js var a = [1,2,3,4]; var b = [4,5,6]; Array.prototype.push.apply(a, b); console.log(a); //[1,2,3,4,4,5,6] 不能去重 ``` > # 七.用0补全位数: ```js function prefixInteger(num, length) { return (num / Math.pow(10, length)).toFixed(length).substr(2); } ``` > # 八.交换值: ```js a= [b, b=a][0]; ``` > # 九.删除数组元素 ```js var a = [1,2,3,4,5]; a.splice(3,1); ``` > # 十.条件判断: ```js var a = b && 1; //相当于 if (b) { a = b; } else { a = 1; } ``` > # 十一.判断IE: ```js var ie = /*@cc_on !@*/false; ``` > # 十二.使用对象构造器 ```js function Person(firstName, lastName){ this.firstName = firstName; this.lastName = lastName; } var Saad = new Person("Saad", "Mousliki"); ``` > # 十三.小心使用typeof、instanceof和contructor ```js typeof:JavaScript一元操作符,用于以字符串的形式返回变量的原始类型,注意,typeof null也会返回object,大多数的对象类型(数组Array、时间Date等)也会返回object instanceof:JavaScript操作符,会在原型链中的构造器中搜索,找到则返回true,否则返回false contructor:内部原型属性,可以通过代码重写 var arr = ["a", "b", "c"]; typeof arr; // 返回 "object" arr instanceof Array // true arr.constructor(); //[] ``` > # 十四.使用自调用函数 函数在创建之后直接自动执行,通常称之为自调用匿名函数(Self-Invoked Anonymous Function)或直接调用函数表达式(Immediately Invoked Function Expression )。格式如下: ```js (function(){ // 置于此处的代码将自动执行 })(); (function(a,b){ var result = a+b; return result; })(10,20) ``` > # 十五.从数组中随机获取成员 ```js var items = [12, 548 , 'a' , 2 , 5478 , 'foo' , 8852, , 'Doe']; var randomItem = items[Math.floor(Math.random() * items.length)]; ``` 最后修改:2021 年 07 月 13 日 © 允许规范转载 打赏 赞赏作者 微信 赞 2 如果觉得我的文章对你有用,请随意赞赏
此处评论已关闭