2016-02-06 40 views
1
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.prootype.slice.call

+0

slice()仅复制所调用对象的数字键后返回新数组。数组有一个.length属性,所以temp.length会告诉你它的长度。 – nnnnnn

回答

3

片的简体版本:

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 
} 

所以实际上切片功能使用[]运营商和this.length财产。这就是它对阵列和类似数组的对象的作用(那些对象具有[].length