suchen

Heim  >  Fragen und Antworten  >  Hauptteil

javascript - In der Map-Implementierung in js, var len = O.length >>> 0;

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

<code>if (!Array.prototype.map) {

  Array.prototype.map = function(callback, thisArg) {

    var T, A, k;

    if (this == null) {

      throw new TypeError(" this is null or not defined");

    }

    var O = Object(this);

    var len = O.length >>> 0;

    // 3.如果callback不是函数,则抛出TypeError异常.

    if (Object.prototype.toString.call(callback) != "[object Function]") {

      throw new TypeError(callback + " is not a function");

    }

    if (thisArg) {

      T = thisArg;

    }

    A = new Array(len);

    k = 0;

    while(k < len) {

      var kValue, mappedValue;

      if (k in O) {

        kValue = O[ k ];

        mappedValue = callback.call(T, kValue, k, O);

        A[ k ] = mappedValue;

      }

      k++;

    }

    return A;

  };     

}</code>

var len = O.length >>> Was ist der Zweck der Bitoperatoren hier?

ringa_leeringa_lee2859 Tage vor929

Antworte allen(3)Ich werde antworten

  • 过去多啦不再A梦

    过去多啦不再A梦2017-05-18 10:59:55

    個人理解:

    因爲雖然這個 map 方法是在Array 的 prototype上的,但實際上調用的時候,this 不一定是 Array類型,length不能得到保證,加上位運算後,可以將不確定的値轉換成Number。

    1

    2

    3

    4

    <code class="javascript">1 >>> 0 // 1

    undefined >>> 0 // 0

    null >>> 0 // 0

    'string' >>> 0 // 0</code>

    Antwort
    0
  • 天蓬老师

    天蓬老师2017-05-18 10:59:55

    将任意JS值转化为数字,且不会出现NaN

    Antwort
    0
  • 天蓬老师

    天蓬老师2017-05-18 10:59:55

    1. 所有非数值转换成0

    2. 所有大于等于 0 等数取整数部分

    Antwort
    0
  • StornierenAntwort