developer
developer

Reputation: 658

For loop withoit indexes javascript

I want to display an array without showing of indexes. The for loop returns the array indexes which is not showing in usual declaration. I want to send an array like [1,2,3 ...] but after retrieving from for loop, I haven't the above format. How can I store my values as above.

var a = [];
for (var i = 1; i < 8; i++) {
    a[i] = i;
};
console.log(a);

Outputs:

[1: 1, 2: 2 ...]

Desired output:

[1,2,3]// same as console.log([1,2,3])

Upvotes: 1

Views: 50

Answers (4)

Acidic
Acidic

Reputation: 6280

I have to disagree with the answers provided here. The best way to do something like this is:

var a = new Array(7);
for (var i = 0; i < a.length; i++) {
    a[i] = i + 1;
}
console.log(a);

Upvotes: 1

Musa
Musa

Reputation: 97717

Array indices start at zero, your loop starts at 1, with index 0 missing you have a sparse array that's why you get that output, you can use push to add values to an array without using the index.

var a = [];
for (var i = 1; i < 8; i++) {
    a.push(i);
};
console.log(a);

Upvotes: 3

dfsq
dfsq

Reputation: 193301

The problem is that you start your array with 1 index, making initial 0 position being empty (so called "hole" in array). Basically you treat array as normal object (which you can do of course but it defeats the purpose of array structure) - and because of this browser console.log decides to shows you keys, as it thinks that you want to see object keys as well as its values.

You need to push values to array:

var a = [];
for (var i = 1; i < 8; i++) {
    a.push(i);
};

Upvotes: 2

void
void

Reputation: 36703

Your code is making each index equal to i, so use it this way

var a = [];
for (var i = 1; i < 8; i++) {
a.push(i);
};
console.log(a);

Upvotes: 0

Related Questions