Javascript reduce函数在这个对象上不起作用

Javascript reduce function doesn't work on this obj

本文关键字:对象 不起作用 reduce 函数 Javascript      更新时间:2023-09-26

我是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中的更多信息在这里