简体   繁体   中英

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?

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")];
...

Yes or you declare your variable like that:

var controlArray = [[],[]];

or

var controlArray = new Array(2);
for (var i = 0; i < 2; i++) {
  controlArray[i] = new Array(2);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM