Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to redefine the + operator on Arrays in JavaScript?

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]
like image 744
Misha Moroshko Avatar asked Mar 31 '12 12:03

Misha Moroshko


People also ask

How do you modify an array in JavaScript?

push() adds item(s) to the end of an array and changes the original array. unshift() adds an item(s) to the beginning of an array and changes the original array. splice() changes an array, by adding, removing and inserting elements. slice() copies a given part of an array and returns that copied part as a new array.

How do you modify data in an array?

To change the value of all elements in an array:Use the forEach() method to iterate over the array. The method takes a function that gets invoked with the array element, its index and the array itself. Use the index of the current iteration to change the corresponding array element.

What is array manipulation in JavaScript?

Array manipulation allows you to do tasks such as add, remove, or transform elements in your array.

How do you use the spread operator to update an array of objects?

let array = [{id:1,name:'One'}, {id:2, name:'Two'}, {id:3, name: 'Three'}]; let array2 = array. map(a => { var returnValue = {...a}; if (a.id == 2) { returnValue.name = "Not Two"; } return returnValue }) console. log(array); console.


1 Answers

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.

like image 102
Pointy Avatar answered Nov 05 '22 23:11

Pointy