Allen S
Allen S

Reputation: 3539

Javascript: Replace everything inside an Array with a new value

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

Answers (5)

defau1t
defau1t

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

kares
kares

Reputation: 7166

you want splice to keep the same instance: arr.splice(0, arr.length, someVar)

Upvotes: 0

Josh
Josh

Reputation: 2895

Try this:

Arr = [somevar];

Demo: http://jsfiddle.net/UbWTR/

Upvotes: 1

Sonu Sindhu
Sonu Sindhu

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

Ivan Chernykh
Ivan Chernykh

Reputation: 42166

Try:

Arr.length = 0;
Arr.push(someVar);

Read more: Difference between Array.length = 0 and Array =[]?

Upvotes: 2

Related Questions