Reputation: 3539
I've got an Array:
var Arr = [1, 4, 8, 9];
At some point later in the code this happens:
Arr.push(someVar);
Here instead of pushing a new value, I want to replace the entire contents of Arr
with someVar
. (i.e. remove all previous contents so that if I console.logged() it I'd see that Arr = [someVar]
How could this be achieved??
Upvotes: 1
Views: 518
Reputation: 10619
You can do like this
var Arr = [1, 4, 8, 9]; // initial array
Arr = [] // will remove all the elements from array
Arr.push(someVar); // Array with your new value
Upvotes: 0
Reputation: 7166
you want splice to keep the same instance: arr.splice(0, arr.length, someVar)
Upvotes: 0
Reputation: 1792
you can assign the value just like this
var Arr = [1, 4, 8, 9]; //first assignment
Arr = [other value here]
It will replace array contents.
I hope it will help
Upvotes: 0
Reputation: 42166
Try:
Arr.length = 0;
Arr.push(someVar);
Read more: Difference between Array.length = 0 and Array =[]?
Upvotes: 2