Javascript的优点:无法理解方法array.push
Javascript the good parts:can't understand method array.push
我正在阅读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)));
任何帮助将不胜感激,谢谢
从内到外执行此操作:
-
Array.prototype.slice.apply(arguments)
---arguments
类似数组的对象转换为真实数组 -
[this.length,0].concat(#1)
--- 将硬编码的[this.length,0]
数组与 #1 中的数组连接
起来 -
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)
;
相关文章:
- Javascript 新的 Array 和 join() 方法
- 为什么我可以在Array属性对象中找到Javascript Array for Each方法
- Array方法中的Javascript循环
- 在Javascript中,当使用array.prush方法向列表中添加项目时,如何对其进行排序
- E4X中是否有一种方法可以将基元数据类型的XMLList转换为类似于Array.join()的Array
- 构造 JavaScript Array 原型方法
- 在 Array.map() 中调用类方法
- Array.insert函数错误,因为Object函数Array(){〔本机代码〕}没有方法'插入'
- TypeError:Object[Object Array]没有方法'getProperty'
- 在Javascript中向Array对象添加一个方法
- 在javascript中扩展Array对象的方法
- CRM 2011 : Object [object Array] 没有方法 'getValue'
- Javascript Array.push 方法问题
- 跨浏览器的方式来子类JavaScript Array并获取array[i]方法
- 从 Array.prototype 方法返回数组的值
- 使用类似于 Array.prototype.map() 的方法将数组转换为键值对象
- JavaScript 方法 array.forEach 在 Chrome 中工作吗?
- ExtJs - 检查 Ext.Array 是否为空的最佳方法
- Javascript的优点:无法理解方法array.push
- 处理 Array.prototype.slice.call(参数)的更简洁方法