0

Possible Duplicate:
Copying array by value in javascript

I am a beginner with javascript, so I would really appreciate any help or advice. I'm trying to get the values that I collect with my inputs array (that are put into a form, by the user, in the document) to set them to the words array. So, I would like inputs[0] = words[0], inputs[1] = words[1] etc. I thought by setting words to an empty array, and then to equal the index value of inputs, that I would achieve this, but it's not working. Words keeps showing up as "undefined".

function goMad() { 
    var words = [];
    var inputs = document.getElementsByTagName("input"); 
    for (var i = 0; i < inputs.length - 1; i++) { 
        inputs[i].value = words;
    }

    var story = words[0] + "! he said " + words[1] + " as he jumped into his convertible " + words[2] + " and drove off with his " + words[3] + " wife.";
    document.getElementById("story").innerHTML = story;

    console.log(words[0]);
}
Community
  • 1
  • 1
user1876829
  • 475
  • 1
  • 7
  • 12
  • Maybe you want it the other way round - to set items in `words`, use `words[i] = inputs[i].value`. – pimvdb Dec 04 '12 at 19:39
  • It might help to understand that `=` is called an "Assignment Operator". You are assigning to the left side with the value of the right side. – Shmiddty Dec 04 '12 at 19:48

1 Answers1

4

Instead of this line:

inputs[i].value = words;

You can use:

words.push(inputs[i].value);

This will add the provided value to the words array. See the MDN docs.

As @pimvdb and @Shmiddty have pointed out you could also use the following. This would behave exactly the same as using push:

words[i] = inputs[i].value;
jabclab
  • 14,786
  • 5
  • 54
  • 51
  • Why you pass this in a function when you can just instanciate the array? – Mike Boutin Dec 04 '12 at 19:41
  • or `words[i] = inputs[i].value;` – Shmiddty Dec 04 '12 at 19:43
  • 1
    @MikeBoutin `inputs` will be an array of DOM elements whereas `words` (I guess) is intended to be an array of `String`s. – jabclab Dec 04 '12 at 19:43
  • @Shmiddty yep, equally valid. – jabclab Dec 04 '12 at 19:44
  • 1
    Thank you everyone. I think the response given by primvdb is originally what I was trying to go for, as I was trying to give words (which, yes, is an array of string values) to the same value as inputs. Seeing the push method used in this way was also very helpful as it seems to accomplish the same thing. Like I said, I am new at this. thanks! – user1876829 Dec 04 '12 at 20:28