问题
Assuming points are represented using JavaScript Array
as [x,y]
, how could I define the +
operator on points such that:
[1,2] + [5,10] == [6,12]
回答1:
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.
回答2:
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
*/
回答3:
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:
- The initial value of the result array should be dynamic
- I haven't tested the code if the arrays aren't of equal length
Good luck!
来源:https://stackoverflow.com/questions/9955926/how-to-redefine-the-operator-on-arrays-in-javascript