为什么angular.lowercase方法使用'按位或32'将'A'转换为'a'?为什么不使用'+ 32'?

时间:2017-08-04 01:37:13

标签: javascript

    var manualLowercase = function(s) {
      return isString(s)
          ? s.replace(/[A-Z]/g, function(ch) {return String.fromCharCode(ch.charCodeAt(0) | 32);})
          : s;
    };
    var manualUppercase = function(s) {
      return isString(s)
          ? s.replace(/[a-z]/g, function(ch) {return String.fromCharCode(ch.charCodeAt(0) & ~32);})
          : s;
    };


    // String#toLowerCase and String#toUpperCase don't produce correct results in browsers with Turkish
    // locale, for this reason we need to detect this case and redefine lowercase/uppercase methods
    // with correct but slower alternatives. See https://github.com/angular/angular.js/issues/11387
    if ('i' !== 'I'.toLowerCase()) {
      lowercase = manualLowercase;
      uppercase = manualUppercase;
    }

以上是角度代码。为什么要使用'ch.charCodeAt(0)| 32'将'A'转换为'a'?为什么不'ch.charCodeAt(0)+ 32'?

1 个答案:

答案 0 :(得分:1)

因为32恰好是2的幂,c | 32等于c + 32如果c & 32 === 0(即c在32的位置有0)。按位运算通常比加法略快,因为计算机可以同时计算所有位,而不必链接进位。