美文网首页
javascript小提示

javascript小提示

作者: kamifun | 来源:发表于2016-09-27 23:11 被阅读0次
    • 字符串可以'借用'数组的非变更方法(调用该方法不影响原数组)
    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' 小数已经有小数点了
    
    • 所有遵循IEEE754规范的语言(JavaScript就是其中之一),在某些小数运算上会出现误差
    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
    
    • 通常在js库中发现void操作符,是为了防止undefined被篡改?
    // 例如:undescore.js中144行,使用void 0,而不是undefined
    var property = function(key) {
        return function(obj) {
          return obj == null ? void 0 : obj[key];
        };
    };
    
    • 位运算符~与indexOf()的基情
      ~x大致等于-(x+1),例如:
    ~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解析字符串
    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
    

    相关文章

      网友评论

          本文标题:javascript小提示

          本文链接:https://www.haomeiwen.com/subject/sffcyttx.html