javascript - Implementation problem of indexof of array?
迷茫
迷茫 2017-06-14 10:54:26
0
1
646

one of them

var O = Object(this);
var len = O.length >>> 0;

What do these two sentences mean?

if (!Array.prototype.indexOf) {
  Array.prototype.indexOf = function(searchElement, fromIndex) {
    var k;
    if (this == null) {
      throw new TypeError('"this" is null or not defined');
    }
    var O = Object(this);
    var len = O.length >>> 0;
    if (len === 0) {
      return -1;
    }
    var n = +fromIndex || 0;
    if (Math.abs(n) === Infinity) {
      n = 0;
    }
    if (n >= len) {
      return -1;
    }
    k = Math.max(n >= 0 ? n : len - Math.abs(n), 0);
    while (k < len) {
      if (k in O && O[k] === searchElement) {
        return k;
      }
      k++;
    }
    return -1;
  };
}
迷茫
迷茫

业精于勤,荒于嬉;行成于思,毁于随。

reply all(1)
我想大声告诉你

Object(this) is not to create a new object, but to convert this into an Object. It is naturally useless for objects that are Objects themselves, such as Array and Object.

O.length >>> 0The three greater-than signs here do not mean that it is always greater than or equal to 0, but a bit operator of JS, which represents an unsigned displacement. The following 0 represents a displacement of 0 bits, but Before JS performs unsigned displacement, it will be converted into an unsigned 32-bit integer for calculation, so >>>0 means converting O.length into a positive integer.

Why do we need these two steps? Isn’t JS’s Array already an Object? Isn't array.length itself definitely a non-negative integer? That’s because this function is a universal function and can be called by non-Array using call. For example:

Array.prototype.indexOf.call("abc","c") // 2

The "abc" here is this in the function body. It is a basic type and needs to be packaged into an Object to use the following in syntax.

0 in "ab" // TypeError
0 in Object("ab") // true

We can use the Array.prototype.indexOf method not only on the basic type, but also on a non-Array Object. At this time, the length is specified by ourselves and cannot be guaranteed to be a positive integer, so it needs to be converted to a non-Array value inside the function. Negative integer.

var obj = {"0":"hello","1":"world",length:2.7568}
Array.prototype.indexOf.call(obj,"world") //1
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template