How to redefine the + operator on Arrays in JavaScript?

烈酒焚心 提交于 2019-12-01 07:16:47

JavaScript does not have a facility for overriding the built-in arithmetic operators.

There are some limited tricks you can pull by overriding the .valueOf() and .toString() methods, but I can't imagine how you could do what you're asking.

You could of course write a function to do it.

How about a nice 'plus' method? This doesn't care how many indexes either array has, but any that are not numeric are converted to 0.

Array.prototype.plus= function(arr){
    var  L= Math.max(this.length,arr.length);
    while(L){
        this[--L]= (+this[L] || 0)+ (+arr[L] || 0);
    }
    return this;
};

[1, 2].plus([5, 10])

/*  returned value: (Array)
[6,12]
*/

[1, 2].plus([5, 10]).plus(['cat',10,5])

/*  returned value: (Array)
6,22,5
*/

I know that's not exactly what you want to do but a solution to your problem is to do something like that:

var arrayAdd = function() {
    var arrays = arguments,
        result = [0, 0];

    for( var i = 0, s = arrays.length; i < s; i++ ) {
        for( var j = 0, t = arrays[ i ].length; j < t; j++ ) {
            result[ j ] += parseInt( arrays[ i ].shift(), 10 );
        }
    }

    return result;
};

var sum = arrayAdd( [1,2], [5,10] ); //Should return [6, 12]

console.log( sum );

PLease note that this code is not final. I see some problems:

  1. The initial value of the result array should be dynamic
  2. I haven't tested the code if the arrays aren't of equal length

Good luck!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!