I have an array that has a bunch of content separated by colons, so for example initArray[0] might have the content 10:30:20:10. How do I split this again so I can have initArray[0][1]. Any help is appreciated!
Felix Kling
820k181 gold badges1.1k silver badges1.2k bronze badges
asked Mar 14, 2012 at 14:15
Johnny
10k5 gold badges34 silver badges36 bronze badges
-
I tried a bunch of things but I couldn't get it to work at all. Javascript is not my forte.Johnny– Johnny2012年03月14日 14:31:44 +00:00Commented Mar 14, 2012 at 14:31
3 Answers 3
If you want to split every element in the array:
for( var i = 0; i < initArray.length; i++ ) {
initArray[i] = initArray[i].split( ':' );
}
So this:
[ '10:30:20:10', 'a:b:c:d' ]
becomes:
[ [ '10', '30', '20', '10' ], [ 'a', 'b', 'c', 'd' ] ]
Sign up to request clarification or add additional context in comments.
1 Comment
Johnny
oh god, I realised what I was doing wrong, I had the i and initArray.length the wrong way around in my for loop. I thought my syntax was flawed.
initArray=new Array('10:30:20:10', '11:31:21:11');
for(i=0;i<initArray.length;i++)
{
initArray[i]=initArray[i].split(':');
}
console.log(initArray[0][0]); // 10
console.log(initArray[1][0]); // 11
answered Mar 14, 2012 at 14:25
The Alpha
147k30 gold badges294 silver badges313 bronze badges
Comments
var tmp = "10:30:20:10".split(":")
alert(tmp[0]) ---> "10"
answered Mar 14, 2012 at 14:18
Diodeus - James MacFarlane
115k33 gold badges164 silver badges180 bronze badges
Comments
lang-js