Javascript reduce函数在这个对象上不起作用
Javascript reduce function doesn't work on this obj
我是Javascript的新手,并试图在父对象上执行下面的代码,但它不像预期的那样工作。请帮助。
下面的代码没有按预期工作,并抛出错误:
" TypeError:这个。Reduce不是一个函数"
Array.prototype.merge = merge = this.reduce(function(arg1,arg2) {
return arg1+arg2;
},[]);
var arrays = [1,2,3,4,5,6];
console.log(arrays.merge);
抛出如下错误:
TypeError: this.reduce is not a function
at Object.<anonymous> (C:'Program Files'nodejs'merge.js:1:100)
at Module._compile (module.js:434:26)
at Object.Module._extensions..js (module.js:452:10)
at Module.load (module.js:355:32)
at Function.Module._load (module.js:310:12)
at Function.Module.runMain (module.js:475:10)
at startup (node.js:117:18)
at node.js:951:3
如果我直接调用array,它工作得很好,但这不是我想要做的。我应该能够传递数组,如上面的示例代码所示。
Array.prototype.merge = merge = [1,2,3,4,5,6].reduce(function(arg1,arg2) {
return arg1+arg2;
},[]);
console.log(arrays.merge);
应该可以了!
Array.prototype.merge = function () {
return this.reduce(function (arg1, arg2) {return arg1 + arg2;},[]);
};
顺便说一下,这是有效的,因为在这种情况下,this
是该方法被调用的对象,它是您的合并函数。
使用Object.defineProperty - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty
Object.defineProperty(Array.prototype, 'merge', {
get: function() { return this.join(''); },
enumerable: false,
configurable: true
});
或-使用reduce
Object.defineProperty(Array.prototype, 'merge', {
get: function() {
return this.reduce(function (arg1, arg2) {
return arg1 + arg2;
}, []);
},
enumerable: false,
configurable: true
});
这段代码将允许你做你在几个注释中所说的
console.log([1,2,3,4,5].merge);
不是console.log([1,2,3,4,5].merge());
我会像这样添加一个合并函数到Array.prototype
:
Array.prototype.merge = function () {
return this.reduce(function (arg1, arg2) {
return +arg1 + +arg2;
}, []);
};
var arrays = [1, 2, 3, 4, 5, 6];
console.log(arrays.merge());
关于this
关键字在Javascript中的更多信息在这里
相关文章:
- JavaScript参数对象不起作用
- Javascript敲除绑定嵌套对象不起作用
- 反应.js - 处于异步数据状态的深层对象不起作用
- 为什么这个对象不起作用
- KnockoutJS - 创建对象不起作用
- Javascript 如果元素不存在返回,则导致对象不起作用
- 通过指令范围传递对象不起作用
- 通过原型扩展数学对象不起作用
- Concat 对象不起作用,或者我需要将值转换为正确的格式
- 使用速记检查未定义的对象不起作用
- 将信息从表单值推送到对象不起作用
- 淘汰:在对象不起作用的情况下进行多选
- 解析函数对Node.js中的promise对象不起作用
- Angularjs指令隔离了对象不起作用的范围+单向数据绑定
- Mongoose - find():搜索选项中的对象不起作用
- 在函数内部生成的对象不起作用,但是传入的对象起作用
- .focus()对克隆对象不起作用
- Ng-click对不透明度为1的对象不起作用
- Javascript对象不起作用
- 将绑定的数据推入对象不起作用