0

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[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)

1
  • temp[0] = {"sky//hi//pi"} is not valid JavaScript. Commented Jul 13, 2011 at 15:20

4 Answers 4

2

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

Sign up to request clarification or add additional context in comments.

Comments

1

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("//");
}

2 Comments

AHHH thanks so much everyone! javascript variable scope confuses the hell out of me -_-
@user839260: This has nothing to do with JavaScript in this case. You would find the same behaviour in any programming language.
1

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

Comments

1

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.