JavaScript - destination - array of arrays

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 would like to have:

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

but actually i have:

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

Can i fix it?

UPD: Raynos solution is really nice. thanks.

+4
source share
3 answers
 for(var i = 0; i < c.length; i++){ c[i].push.apply(c[i], str.split(',')); } 
+5
source

The split function creates a new array, which is stored in c . You need to go through the array returned by split and make c[i].push() at that value.

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

+1
source

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

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

0
source

Source: https://habr.com/ru/post/1379702/


All Articles