非常教程

JavaScript参考手册

Math

Math.clz32

Math.clz32()函数返回一个数字在转换成 32 无符号整形数字的二进制形式后, 开头的 0 的个数。

语法

Math.clz32(x)

参数

x一个数值。

返回值

给定数字的32位二进制表示中前导零位的数量。

描述

"clz32" 是 CountLeadingZeroes32的缩写.

如果 x 不是数字类型, 则它首先会被转换成数字类型, 然后再转成 32 位无符号整形数字. 

如果转换后的 32 位无符号整形数字是 0, 则返回32, 因为此时所有位上都是 0.

这个函数主要用于那些编译目标为 JS 语言的系统中, 比如 Emscripten.

示例

使用Math.clz32()

Math.clz32(1);                // 31
Math.clz32(1000);             // 22
Math.clz32();                 // 32

[NaN, Infinity, -Infinity, 0, -0, null, undefined, 'foo', {}, []].filter(
function(n) {
  return Math.clz32(n) !== 32
});                           // []

Math.clz32(true);             // 31
Math.clz32(3.5);              // 30

Polyfill

以下polyfill是最有效的。

if (!Math.clz32) {
  Math.clz32 = function(x) {
    // Let n be ToUint32(x).
    // Let p be the number of leading zero bits in 
    // the 32-bit binary representation of n.
    // Return p.    
    if (x == null || x === 0) {
      return 32;
    }
    return 31 - Math.floor(Math.log(x >>> 0) * Math.LOG2E);
  };
}

规范

Specification

Status

Comment

ECMAScript 2015 (6th Edition, ECMA-262)The definition of 'Math.clz32' in that specification.

Standard

Initial definition.

ECMAScript Latest Draft (ECMA-262)The definition of 'Math.clz32' in that specification.

Draft

浏览器兼容性

Feature

Chrome

Firefox

Edge

Internet Explorer

Opera

Safari

Basic Support

38

31

(Yes)

(No)

25

(Yes)

Feature

Android

Chrome for Android

Edge mobile

Firefox for Android

IE mobile

Opera Android

iOS Safari

Basic Support

(Yes)

(Yes)

(Yes)

31

(No)

(Yes)

(Yes)

JavaScript

JavaScript 是一种高级编程语言,通过解释执行,是一门动态类型,面向对象(基于原型)的解释型语言。它已经由ECMA(欧洲电脑制造商协会)通过 ECMAScript 实现语言的标准化。它被世界上的绝大多数网站所使用,也被世界主流浏览器( Chrome、IE、FireFox、Safari、Opera )支持。JavaScript 是一门基于原型、函数先行的语言,是一门多范式的语言,它支持面向对象编程,命令式编程,以及函数式编程。它提供语法来操控文本、数组、日期以及正则表达式等,不支持 I/O,比如网络