javascript simultaneously push elements of two arrays into one array -
i'm trying find javascript code simultaneously enters data 2 arrays , places them 1 array. thought work, looking on it, doesn't quite job.
var tempdeck = []; var array1 = ["one", "two"]; var array2 = ["three", "four"]; (i = 0; < array1.length + array2.length; i++){ if (i % 2 == 0){ tempdeck.push(array1[i]); }else{ tempdeck.push(array2[i]); } } i need output result of
tempdeck[0] = "one"; tempdeck[1] = "three"; tempdeck[2] = "two"; tempdeck[3] = "four"; i'm trying avoid manually placing them in, because number or arrays based on user input. :( suggestions?
you should use length of larger array, , add if value exists @ index i.
var tempdeck = []; var array1 = ["one", "two"]; var array2 = ["three", "four"]; var len = array1.length > array2.length ? array1.length : array2.length; (i = 0; < len; i++){ if( array1.length > )tempdeck.push(array1[i]); if( array2.length > )tempdeck.push(array2[i]); }
Comments
Post a Comment