简体   繁体   English

Javascript减少功能不适用于此obj

[英]Javascript reduce function doesn't work on this obj

I am new to Javascript and trying to execute below code on parent object but it is not working as expected. 我是Java的新手,正尝试在父对象上执行以下代码,但未按预期工作。 Please help. 请帮忙。

The below code doesn't work as expected and throws error as: 下面的代码无法正常工作,并引发错误:

"TypeError: this.reduce is not a function" “ TypeError:this.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);

It throws error as below: 它引发如下错误:

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

If I call array directly, it works fine but that is not what I want to do. 如果我直接调用数组,它可以正常工作,但这不是我想要的。 I should be able to pass array as shown on above example code. 我应该能够像上面的示例代码所示那样传递数组。

Array.prototype.merge = merge = [1,2,3,4,5,6].reduce(function(arg1,arg2)   {
    return arg1+arg2;
},[]);

console.log(arrays.merge);

This should do the trick! 这应该可以解决问题!

Array.prototype.merge = function () {
    return this.reduce(function (arg1, arg2) {return arg1 + arg2;},[]);
};

By the way, this works because in this case, this is the object that the method is being called on, which is your merge function. 顺便说一句,之所以可行,是因为在这种情况下, this是调用方法的对象,这是您的合并功能。

Use Object.defineProperty - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty 使用Object.defineProperty- https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty

Object.defineProperty(Array.prototype, 'merge', {
  get: function() { return this.join(''); },
  enumerable: false,
  configurable: true
});

or - using reduce 或-使用reduce

Object.defineProperty(Array.prototype, 'merge', {
  get: function() { 
    return this.reduce(function (arg1, arg2) {
      return arg1 + arg2;
     }, []); 
  },
  enumerable: false,
  configurable: true
});

This code will allow you to do what you've said in a couple of comments 此代码将使您能够执行您在一些注释中所说的

console.log([1,2,3,4,5].merge);

instead of 代替

console.log([1,2,3,4,5].merge());

I would add a merge function to the Array.prototype like this: 我会像这样向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());

More about the this keyword in Javascript here . 有关Java中this关键字的更多信息,请点击此处

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM