Javascript的优点:无法理解方法array.push

Javascript the good parts:can't understand method array.push

本文关键字:方法 array push Javascript      更新时间:2023-09-26

我正在阅读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. 起来
  4. this.splice.apply(this, #2) --- 将 this.splice 函数应用于具有 #2 中参数this对象

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

引用:

  • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice

apply接受一个函数,并在提供的this对象和从数组中获取的参数上调用它。

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

所以,我们在这里拥有的是:

this.splice        // a reference to the function "splice" that an Array has
this.splice.apply  // invoke this function 
this.splice.apply(this   // invoke it on "this" 
this.splice.apply(this,[     // with an array of parameters
    [this.length,0]   // the first two parameters are "the length", and a "0"
    // calling splice this way means replacing the 0 elements 
    // after the end of the array with the following new elements
    // => i.e. pushing the new elements 
    ].concat     // but we add some more parameters
    Array.prototype.slice.apply(arguments)    
        // namely the arguments passed into this function

最后一步是必要的,因为arguments不是真正的数组,所以它不适用于 concat。 slice复制它(到一个真实的数组中)。

用一个例子总结一下。

如果您调用[1,2,3].mypush(2,3)则转换为[1,2,3].splice(3, 0, 2, 3);