1

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])
1
  • 1
    The resulted array is correct (except it holds undefined at the first index). The output in the console is just formatted in a different way. Commented Feb 15, 2015 at 18:02

4 Answers 4

3

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);
Sign up to request clarification or add additional context in comments.

Comments

2

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);
};

Comments

1

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);

11 Comments

Can you please explain, why would this be the best way? This doesn't even put the numbers OP needs to the array.
Because this way allocates the required size in one go, while creating a 0-length array and increasing it size gradually will most likely require re-allocating memory blocks multiple times (depends on the final size of the array).
I'm appreciating your explanation. Thanks.
Afaik defining an empty array using [] is preferred nowadays. new Array() should be avoided because of some inconsistencies of it when using arguments. Looks like you've fixed the content issue though.
@Teemu Yes, I did fix the content, thanks to your comment. What inconsistencies are there with new Array(size)?
|
0

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);

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.