JavaScript Array Manipulation: Issues with forEach
When i want to modify an array like below, it doesn't modify the original array. Why is that?
If i change the
arr = arr.map((item) => item = "");
to gameBoard[index] = arr.map((item) => item = "");
it works as expected and modify the original array. What is the difference here?130 Replies
Array.map() creates and returns a new array, it does nothing to the original.
Array.forEach(), on the other hand, doesn’t create a new array or return any value. Instead, it performs a function on each value inside the array.
Also, the
forEach()
method takes a function that has the item and index, not the array and index
So of course the item will be the same as the gameBoard[index]
:pYes, know that but, my logic is that
arr
is an object that has a reference to an array (depends on the index) inside the gameBoard so, i think i can change it but, this isn't the right logic it seems. I'm confused with arr here actually.What exactly are you trying to do? Your code is a bit confusing so I’m not sure what the current results are vs what want them to be
Also, what does an item in your game board array look like?
I want to change the array. This array has three sub arrays and i want to access all of them and change their values to "". So, i thought if i forEach the gameBoard array; arr parameter gives me arrays inside gameboard Arrays and i can change this arrays.
Sorry, if i misleading you to wrong direction
and gameBoard array is 2D array.
it has 3 arrays inside it
and they have 3 empty strings
I will change to my phone because i will go to my home but, i want to talk about it if you have time.
is this for tictactoe?
yes
why dont you use a single flat array?
actually, i dont know. You are right about it 🙂 but, i want to know why this behaviour happens though
If you’re resetting everything why do a recursive search? Why not just set the main game board to a new, empty/reset array?
^
also, foreach doesnt update the array values
Yes guys, you are right about your implementations and mine is bad i know it. I just wonder why in this situation JS behaves like that
you are updating a local variable inside a foreach
and that's it
the value will be lost
it behaves like that because foreach is the wrong tool
But why gives true when i check the equality between them
copy on write?
i think v8 uses that
Arrays are shallow copies, so you’re comparing, in essence, the exact same thing