0

This is a really stupid question, but I'm just drawing a blank here...

What type of variable declaration is this:

var s1 = [1,2,3,4]

Also, How can I construct a variable like this from multiple objects when the amount of those objects is unknown. This is what I came up with, which doesn't work.

var s1 = [];
for(x in data[i].uh) {
    s1 += data[i].uh[x];
}
1

6 Answers 6

2
var s1 = [1,2,3,4]

is an array declaration of four integers using "Array Literal Notation"

You don't need a loop to copy the array, simply do this:

var s1 = data.slice(0);

or in your example you might want this:

var s1 = data[i].uh.slice(0);

Read more about copying arrays here: http://my.opera.com/GreyWyvern/blog/show.dml/1725165

"The slice(0) method means, return a slice of the array from element 0 to the end. In other words, the entire array. Voila, a copy of the array."

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

2 Comments

Be careful with duplicating an array using slice as it is a reference copy and not a value copy. Meaning if you change one you change the other.
@The_asMan No, it copies the array. Consider this code: var foo = [1,2,3,4,5]; alert(foo[2]); /* Returns 3 */ var bar = foo.slice(0); alert(bar[2]); /* Returns 3 */ bar[2] = 0; alert(bar[2]); /* Returns 0 */ alert(foo[2]); /* Returns 3 */ w3schools.com/jsref/jsref_slice_array.asp
2

That is called an Array, which can be declared with new Array() or by using the array literal [] as in your example. You can use the Array.push() method (see docs) to add a new value to it:

var s1 = [];
for(x in data[i].uh) {
    s1.push(data[i].uh[x]);
}

1 Comment

Oh wow. Okay, I thought array's had to be declared with new Array().
2

This

var s1 = [1,2,3,4]

is an array declaration.

To add an element to an array, use the push method:

var s1 = [];
for(x in data[i].uh) {
    s1.push(data[i].uh[x]);
}

Comments

2

s1 is an array, it's a proper Javascript object with functions.

var s1 = [];

is the recommend way to create an array. As opposed to:

var s1 = new Array();

(see: http://www.hunlock.com/blogs/Mastering_Javascript_Arrays)

To add items to an array use s1.push(item) so your code would be:

var s1 = [];
for(x in data[i].uh) {
    s1.push(data[i].uh[x]);
}

As a side note, I wouldn't recommend using for-in, at least not without checking hasOwnProperty.

Comments

1

It's declaring a local variable with an Array with 4 members.

If you want to append to an Array, use the push() method.

Comments

1

That is an array. To add to arrays you would use Array.push(). For example:

var s1 = [];
s1.push(1);
s1.push(2);

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.