开发者

filling a multidimensional array in javascript

开发者 https://www.devze.com 2023-03-20 05:41 出处:网络
I start out with an array of strings where each element of the array is separated by \"//\". e.g. temp[0] = {\"sky//hi//pi\"} , temp[1] = {\"fish//steak//carrot\"}. Now my code looks like this:

I start out with an array of strings where each element of the array is separated by "//". e.g. temp[0] = {"sky//hi//pi"} , temp[1] = {"fish//steak//carrot"}. Now my code looks like this:

for (var i = 0; i < temp.length ;i++)
{
window.data_arrays = Array(2);
window.data_arrays[i] = temp[i].split("//");
}

What I'm trying to do is to make data_arrays into a 2 dimensional array...so for the example it would be like temp[0][0] = "sky", temp开发者_JS百科[0][1] = "hi", temp[1][0] = "fish".

However the code doesn't work. Can someone please help me out? Thanks. (reason why I'm assigning it to window is because I need to access this variable in another file later)


Assuming your temp array is correct, you have to initialize the array before the loop:

window.data_arrays = [];
for (var i = 0; i < temp.length; i++) {
     window.data_arrays[i] = temp[i].split("//");
}

Otherwise you overwrite it on every iteration and it will only contain the values of the last iteration.

DEMO


You were close.

temp = []; 
temp[0] = "sky//hi//pi"; 
temp[1] = "fish//steak//carrot";

window.data_arrays = [];
for (var i = 0; i < temp.length ;i++) {
  window.data_arrays[i] = temp[i].split("//");
}


In your sample code line 3 (below), "window.data_arrays" is overwritten in each iteration.

window.data_arrays = Array(2);

By moving the assignment statement to outside of loop. The following code worked for me. (I used the FireBug plugin in firefox)

var temp = ["sky//hi//pi","fish//steak//carrot" ];

var data_array = {};
for (var i = 0; i < temp.length ;i++)
{
   data_array[i] = temp[i].split("//");
}

console.log(data_array.length);
console.log(data_array[0][0]);
console.log(data_array[0][1]);
console.log(data_array[0][2]);
console.log(data_array[1][0]);


the array definition is malformed, the rest is close:

var temp = [];
temp.push("sky//hi//pi");           // temp[0]
temp.push("fish//steak//carrot");   // temp[1]

var final = [];
for( var i=0, tempLen=temp.length; i < tempLen; i++ ){
   final.push( temp[i].split("//"));
}
console.log(final);
0

精彩评论

暂无评论...
验证码 换一张
取 消