var arrayMethods = [
'push',
'pop',
'shift',
'unshift',
'splice',
'sort',
'reverse'
];
var arrayAugmentations = [];
arrayMethods.forEach(function (item) {
var originalMethod = Array.prototype[item];
arrayAugmentations[item] = function () {
return originalMethod.apply(this, arguments)
}
});
console.log(arrayAugmentations.length);//为什么是0?
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
这段, 相当于是在 arrayAugmentations 这个数组实例上添加方法了,
而不是把这个函数推到数组里, 当成数组成员.
代码中
arrayAugmentations被定义为数组,全过程又没有push操作,当然length为0。从程序意图上看,
arrayAugmentations应定义为对象。你没搞清楚forEach回调函数的每个参数
看看Array.prototype.forEach
你这里的item指的是
arrayMethods数组中的每一项成员这样才是给
arrayAugmentations添加成员其实js数组也是一种特殊的object,数组的key只能是数字,而不能是string。你上面代码最大的错误就是用了string作为数组的key,这样赋值是不会成功的,因此你最终console的时候打印不了数组的length。