1

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??

1
  • did you try simply assigning the new value?? Arr = [someVar] Commented Jul 30, 2013 at 11:16

5 Answers 5

2

Try:

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

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

Sign up to request clarification or add additional context in comments.

Comments

1

Try this:

Arr = [somevar];

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

1 Comment

... that does not replace the contents but creates a new one :)
0

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

1 Comment

This replaces the array with a value, not with a new array containing the value. (note - comment based on version without square brackets)
0

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.