How do you explain this behavior of the map function?
-
little experience in js. And the question is most likely stupid, but still did not find information about this.
let cord = [{x: 0, y: 0, type: 5, active: true}] console.log(cord) //x=5 cord.map(elem => elem.x = 5) console.log(cord) //x=5
as far as I know, map produces a new array, the variable of which needs to be equatedJavaScript Molly Rowe, Feb 12, 2020 -
In this case, the anonymous function in map changes the property x directly in the object - an array element that is passed to it by reference.
The map function also has a result, it is [5].Anonymous -
const cord = [{x: 0, y: 0, type: 5, active: true}]
console.log(cord) // x = 0
const newCoord = cord.map(elem => ({
...elem,
x: 5
}))
console.log(cord) // x = 0
console.log(newCoord) // x = 5Milo Riggs -
In your case, something like this happens:
function incrementX(obj) {
obj.x += 1
return obj
}
var a = {x: 0}
var b = incrementX(a)
console.log(b) // {x: 1}
console.log(a) // {x: 1} -- Магия
Objects in JS are passed by reference. That is, passing an object as an argument to a function, the latter can modify it, which can lead to undesirable effects.Anonymous
3 Answers
Your Answer
To place the code, please use CodePen or similar tool. Thanks you!