我无法理解Array.prootype.slice.call

I can't understand Array.prootype.slice.call

本文关键字:prootype slice call Array      更新时间:2023-09-26
temp = {0:'one', 1:'two', 2:'three', 3:'four',length:4};
console.log( Array.prototype.slice.call( temp, 1));
//["two", "three", "four"]

为什么会这样呢?length物业在哪里?叫Array.prototype.slice.call( temp, 1)的时候不应该["two", "three", "four", 4]吗?

切片的简化版本:

Array.prototype.slice = function(a, b) {
  a = a || 0
  if (a < 0) a += this.length
  b = b || this.length
  if (b < 0) b += this.length
  var ret = []
  for (var i = a; i < b; i++)
    ret.push(this[i])
  return ret
}

所以实际上切片函数使用[]运算符和.length属性this。这就是它在数组和类似数组的对象(那些具有[].length的对象)上的工作方式