javascript小提示

2016-09-27  本文已影响0人  kamifun
var a = 'abcd';
// 非变更方法
console.log(Array.prototype.join.call(a, '-')); // 'a-b-c-d'
console.log(Array.prototype.map.call(a, function (str) {
    return str.toUpperCase() + '.';
}).join()); // 'A.B.C.D.'
……
// 变更方法
console.log(Array.prototype.reverse.call(a)); // Uncaught TypeError: Cannot ……
// 无效语法
1.toFixed(3); // Uncaught SyntaxError: Invalid or unexpected token
// 正确语法
(1).toFixed(3); // '1.000'
1..toFixed(3); // '1.000'
1['toFixed'](3); // '1.000'
1 .toFixed(3); // '1.000' 注意1后面有空格,不推荐使用,会引起误会
0.1.toFixed(3); // '0.100' 小数已经有小数点了
0.1 + 0.2 === 0.3; // false
0.1 + 0.2; // 0.30000000000000004
// ES6
Number.isInteger(1); // true
Number.isInteger(1.0); // true
Number.isInteger(1.1); // false
typeof NaN; // 'number'
NaN != NaN; // true
// 例如:undescore.js中144行,使用void 0,而不是undefined
var property = function(key) {
    return function(obj) {
      return obj == null ? void 0 : obj[key];
    };
};
~42; // -(42+1) -> -43

也就是说~-1就是0,而0转换为布尔值是false。再看indexOf()在未索引到时返回的是-1,结合~-1知道-1代表着失败,是不是满满的基情--
因此我们在判断是否索引到时,可以使用~操作符,而不用判断== -1:

var a = 'hello world';
// 原来的判断
if (a.indexOf('lo') != -1) {
    // 找到匹配!
}
// 使用~
if (~a.indexOf('lo')) {
    // 找到匹配
}
parseInt(1/0, 19); // 18 过程:1/0 -> 'Infinity' -> 'i' -> 18
parseInt(false, 16); // 250 过程:false -> 'false' -> 'fa' -> 250
parseInt(parseInt, 16); // 15 过程:parseInt -> "function parseInt() { [native code] }" -> 'f' -> 15

解析:parseInt第一个参数只接受字符串,而传递非字符串时会先转换为字符串;第二个参数是基数,例如基数为19时,0-9 && a-i分别代表0-18、基数为16时,0-9 && a-f分别代表0-15;

// &&逻辑与,当条件判断(运算符左边操作数)为true,则返回第二个操作数,反之返回第一个,类似于三元运算符
1 && 0; // 0
0 && 1; // 0
1 ? 0 : 1; // 0
// ||逻辑或,当条件判断(运算符左边操作数)为true,则返回第一个操作数,反之返回第二个,类似于三元运算符
1 && 0; // 1
0 && 1; // 1
1 ? 1 : 0; // 1
上一篇下一篇

猜你喜欢

热点阅读