gpt4 book ai didi

Javascript 好的部分 :can't understand method array. 推送

转载 作者:行者123 更新时间:2023-11-30 08:01:33 26 4
gpt4 key购买 nike

我正在阅读 Douglas Crockford 的 Javascript 的好部分,但我无法理解第 8 章方法中 Array.push 的实现,如下:

Function.prototype.method = function(name,func){
if(!this.prototype[name]){
this.prototype[name] = func;
}
};

Array.method('mypush',function(){
this.splice.apply(this,[this.length,0].concat(Array.prototype.slice.apply(arguments)));

return this.length;
});

var arr = [1,2,3];
arr.mypush(2,3);
console.log(arr);

我无法理解这个说法:

this.splice.apply(this,[this.length,0].concat(Array.prototype.slice.apply(arguments)));

任何帮助将不胜感激,谢谢

最佳答案

由内而外:

  1. Array.prototype.slice.apply(arguments) --- 将arguments类数组对象转换为真正的数组
  2. [this.length,0].concat(#1) --- 将硬编码的[this.length,0] 数组与来自#1 的数组连接起来
  3. this.splice.apply(this, #2) --- 将 this.splice 函数应用于 this 对象,参数来自#2

最后它看起来像:this.splice(this.length, 0, arg1, arg2, arg3) 这意味着:在索引等于 this.length (请参阅“最后”)用给定的参数替换 0 元素(请参阅 - 不要删除任何内容)。

引用资料:

关于Javascript 好的部分 :can't understand method array. 推送,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26900626/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com