victor
victor

Reputation: 55

'Variable' variables not working in javascript

im practicing javascript .

and im trying using array element as array name in Javascript .

i searchd stackoverflow and found some links like this

when im testing this i found that its not working, it gives undefind when im calling the second function. please see the jsbin link , maybe im getting it wrong please help me out. here is my code , and link: https://jsbin.com/yazowutera/

<button onclick="testArrays1(a, [vic.zero, vic.one])">source</button>
<br>
<button onclick="testArrays2(a, vic[all[1]])">desti</button>

and javascript

<script>

var vic = {

    zero : ["00","01","02"],

    one : ["10","11","12"],

    two : ["20","21","22"]

};
var all = ["zero","one","two"];

var a = "a";


function testArrays1(needle, arrays){
    for (var i=0; i<arrays.length; i++) {
        alert(needle +arrays[i]);
    }
}

function testArrays2(needle, arrays) {
  //for (var i=0; i<arrays.length; i++) {
    alert(needle +arrays);
  //}
}

</script>

im not in j-query right now please ans in javascript

Upvotes: -1

Views: 80

Answers (3)

NiRUS
NiRUS

Reputation: 4259

As metioned by others all is a reserved keyword. But if you still want to use it you can use as below. Which works!

Remember: Always using a reserved keyword as variable in JavaScript coding is a bad practice. So refrain using those reserved words.

Your Javascript:

window.all = ["zero","one","two"];

Your HTML:

<button onclick="testArrays2(a, window.all[1])">desti</button>

Upvotes: 0

musefan
musefan

Reputation: 48415

It seems that all is a special variable reserved for HTMLAllCollection and the second element of it (i.e. all[1]) is a HTMLHeadElement. This only seems to applicable when working with inline scripts (scripts in element attributes). It seems you have to do document.all if using normal script blocks (but this may be caused as a side-effect of testing with JSFiddle).

The recommended solution is to use a different variable name. For example, change the variable to test:

<button onclick="testArrays2(a, vic[test[1]])">desti</button>

var test = ["zero","one","two"];

Upvotes: 1

kanzelm3
kanzelm3

Reputation: 535

"all" (or "document.all") is a reserved variable that returns an HTMLAllCollection. Change your variable name to something else in your javascript and it will work.

Upvotes: 1

Related Questions