day218-[].slice.call(arguments)

要点

  1. 类数组的转换
  2. call绑定其他对象的上下文
  3. slice方法中的for…in

类数组的转换

[].slice.call(arguments)

call绑定其他对象的上下文

var sliced = Array.prototype.slice.call({'0': 'a', '1': 'b', '2': 'c', length: 3}, 2);
// [ 'c' ]
var sliced = Array.prototype.slice.call({'0': 'a', '1': 'b', '3': 'c', length: 3}, 2);
// [ <1 empty item> ]

slice方法中的for…in

Array.prototype.mockSlice = function(begin, end) {
// IE < 9 gets unhappy with an undefined end argument
end = (typeof end !== 'undefined') ? end : this.length;
// For array like object we handle it ourselves.
var i, cloned = [],
size, len = this.length;

// Handle negative value for "begin"
var start = begin || 0;
start = (start >= 0) ? start : Math.max(0, len + start);

// Handle negative value for "end"
var upTo = (typeof end == 'number') ? Math.min(end, len) : len;
if (end < 0) {
upTo = len + end;
}
// Actual expected size of the slice
size = upTo - start;

if (size > 0) {
cloned = new Array(size);
if (this.charAt) { // String,如果是字符型返回指定位置的字符
for (i = 0; i < size; i++) {
cloned[i] = this.charAt(start + i);
}
} else {
for (i = 0; i < size; i++) {
cloned[i] = this[start + i]; // 迭代数组
}
}
}

return cloned;
};

function foo (a, b, c) {
console.log([].mockSlice.call(arguments)) // [ 'a', 'b', 'c' ]
}
foo('a', 'b', 'c')

参考

Array.prototype.slice()

how does Array.prototype.slice.call() work?

Array.prototype.slice method description

文章作者: lmislm
文章链接: http://lmislm.com/2019/08/19/2019-08-19/
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 LMISLMのBlog