2

I have been trying to populate an array using a for loop and taking such values using document.getElementById("spin " + i).value;

The ids on my html for every input tag go from spin1 to spin18.

Any suggestions on what I am doing wrong? Or what I can change?

var nums = [];

for(var i = 1; i <= 18; i++){
    var num[i] = parseInt(document.getElementById("spin" + i).value);

    nums.push(num[i]);

}

alert(nums.length);
2
  • What error you are getting? and please share your HTML as well. Commented Mar 18, 2013 at 6:34
  • 3
    var num[i] doesn't work. You can't create an array that way. Do var num = parseInt(...); nums.push(num); Commented Mar 18, 2013 at 6:36

3 Answers 3

6

What is the problem? You never mention what kind of results being generated or what the front-end html code looks like.

The js looks compilable, but here are some pointers.

The number 0 is before 1

It's a good habit to get in this mind set, plus it might save you from making stupid mistakes later on. Anyway, just to reinforce this, below is a number chart.

    0      10
    1      11
    2      12
    3      13
    4      14
    5      15
    6      16
    7      17
    8      18
    9      19

Avoid unnecessary variables

Having a js compiler that optimizes redundant code is sadly new feature. But still, why have two lines to maintain when you can have one.

var nums = [];

for( var i = 0; i < 18; i++ ) {
    nums[i] = parseInt( document.getElementById("spin" + i).value );
}

Don't push, insert

The push method has an expensive overhead so use it with caution.

Loggers

The console has a built in logger, why not use that instead of an alert box?

console.log( nums.length );
Sign up to request clarification or add additional context in comments.

1 Comment

I agree with Dam. According to this test, .push will significantly slower your code if you have a lot of them.
1

try this

var nums = [];

for(var i = 1; i <= 18; i++){
    var num= parseInt(document.getElementById("spin" + i).value);

    nums.push(num);

}

alert(nums.length);

Comments

1

A couple of things to note:

  1. As PSR has mentioned, you use:
var num[i]

when it should be

var num
  1. getElementById(id).value only works for form elements, you have to use .innerHTML for divs.

This works for me: http://jsfiddle.net/sbqeT/

4 Comments

getElementById(id).value only works for input elements Not true, consider this example.
@Derek: You are correct, would "form elements" be a more correct term?
"Form elements" sounds better.
Thanks for addressing the difference between innerHTML and value! It solved my problem!

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.