4
var a = new Array();
var b = new Array();
var c = [a,b];

var str = 'hello,world,nice,day';
for(var i = 0; i < c.length; i++){
  c[i] = str.split(',');
}

After execution i'd like to have:

c = [a, b];
a = ['hello', 'world', 'nice', 'day'];
b = ['hello', 'world', 'nice', 'day'];

but really i have:

c = [['hello', 'world', 'nice', 'day'], ['hello', 'world', 'nice', 'day']];
a = [];
b = [];

could i fix it?

upd: Decision by Raynos is really nice. Thx.

2
  • I'm surprised you get a=null,b=null, shouldn't a and b be empty arrays? Commented Nov 4, 2011 at 19:21
  • When i wrote a=null, b=null it's mean they are empty arrays. Sorry for my mistake. Commented Nov 4, 2011 at 19:22

3 Answers 3

5
for(var i = 0; i < c.length; i++){
  c[i].push.apply(c[i], str.split(','));
}
Sign up to request clarification or add additional context in comments.

Comments

1

The split function creates a new array, that is stored in c. You have to loop through the array returned by split and do c[i].push() on that value.

Or just set a and b directly to the result of split.

Comments

0

Because you wrote c[i] = str.split(','); - you should write c[i] = str.split(',')[i];
And actually - why go over it with for?

Edit - Sorry, thought the assignment was to c[0], c[1]....

3 Comments

str.split(',')[i]. Are u sure about answer?
that doesn't do what he wants at all
I'm sure about the syntax - but I've edited my answer, didn't noticed the first part of c = [a,b]

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.