javascriptarraystype-2-dimension

Javascript two dimensional array initialization


Meet with a really weird javascript problem. See my codes below:

function initBadScripts(controlArray) {
    var scriptsLine = prompt("Please enter the bad scripts", "debug");

    if (scriptsLine != null) {
        var pattern = /;/;
        var nameList = scriptsLine.split(pattern);
        alert(nameList+" "+nameList.length);
        for(var counter = 0; counter < nameList.length; counter++){
           controlArray[counter][0]=true;
           controlArray[counter][1]= new RegExp(nameList[counter],"g");
           alert(controlArray[counter][0]);
        }
    }
    alert("wtf!");
}

var controlArray = [[]];
initBadScripts(controlArray);

I defined a function, and call that function. A 2-dimensional array called 'controlArray' is defined with no value. Basically, the function check the user's input and use regular expression to make a 'namelist'. For example, if the user type in

ExampleOne;ExampleTwo

The function will create an array called 'nameList'

nameList=[ExampleOne,ExampleTwo];

Then I want to make a dynamical initialization of the 2-dimensional array called 'controlArray', according to the length of nameList. However this only works fine the nameList'length is 1. If it exceeds one (the user type in 'ExampleOne;ExampleTwo'), the ExampleTwo does not go into the array, and the

alert("wtf");

doesn't run at all. This seems that there is already an error before it. Any comments?


Solution

  • JavaScript doesn't have a true 2-dimensional array. Rather, you're putting a second array inside the first array. Change it to this:

    ...
    for(var counter = 0; counter < nameList.length; counter++){
           controlArray[counter] = [true, new RegExp(nameList[counter],"g")];
    ...