javascript - 这段代码有什么问题
PHP中文网
PHP中文网 2017-04-11 13:05:23
[JavaScript讨论组]
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?
PHP中文网
PHP中文网

认证0级讲师

全部回复(5)
PHPz
arrayAugmentations[item] = function () {
    return originalMethod.apply(this, arguments)
}

这段, 相当于是在 arrayAugmentations 这个数组实例上添加方法了,
而不是把这个函数推到数组里, 当成数组成员.

PHP中文网

代码中arrayAugmentations被定义为数组,全过程又没有push操作,当然length为0。

从程序意图上看,arrayAugmentations应定义为对象。

var arrayAugmentations = {};
ringa_lee

你没搞清楚forEach回调函数的每个参数
看看Array.prototype.forEach

你这里的item指的是arrayMethods数组中的每一项成员

arrayMethods.forEach(function (item, index) {
    var originalMethod = Array.prototype[item];

    arrayAugmentations[index] = function () {
        return originalMethod.apply(this, arguments)
    }

});

这样才是给arrayAugmentations添加成员

天蓬老师

其实js数组也是一种特殊的object,数组的key只能是数字,而不能是string。你上面代码最大的错误就是用了string作为数组的key,这样赋值是不会成功的,因此你最终console的时候打印不了数组的length。

ringa_lee
  var a = [];
  a['push'] = 'html';
  a[0] = 'css';
  a[-1] = 'js';
  a[0.2] = 'vue.js';
  a[1] = 'ajax';
  a['sort'] = 'php';
  a['2'] = 'c#';
  console.log(a.length); // 3;
  console.log(a);
  console.log(a.push); // 'html
  console.log(a.hasOwnProperty('push')); // true
  console.log(a.hasOwnProperty('slice'),a.slice); // false function slice { [native code] }
  console.log(Array.prototype.push); // function push() { [native code] }
// 应该 要 整数 (不包括负数) 才 能 改变 数组 的 length 罢?
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号