i have some value stored in array and i wana split them and wana know length of its contains value but when i am running function it is not working
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(function(){
var valData= ['songs','video','movie','games','other'];
var valNew=valData.split(',');
for(i=0;i<valNew.length;i++);
alert(valNew.length)
})
</script>
</head>
<body>
<select id="me"></select>
</body>
-
You are not using a bit of jQuery in this code.kapa– kapa2012年04月21日 09:11:08 +00:00Commented Apr 21, 2012 at 9:11
-
2@bažmegakapa he is using the shorthand for $(document).ready(), although it is not relevant to the questionKevin Bowersox– Kevin Bowersox2012年04月21日 09:14:28 +00:00Commented Apr 21, 2012 at 9:14
-
1@kmb385 Yeah, that's true, but even that is not needed, there is no DOM access in the code.kapa– kapa2012年04月21日 09:24:13 +00:00Commented Apr 21, 2012 at 9:24
5 Answers 5
Split is used to separate a delimited string into an array based upon some delimiter passed into the split function. Your values are already split into an array. Also your for loop syntax is incorrect.
Split Documentation: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/split
Corrected code:
$(function(){
var valData= "songs,video,movie,games,other";
var valNew=valData.split(',');
for(var i=0;i<valNew.length;i++){
alert(valNew.length)
}
});
3 Comments
length AND declare i as local (it is GLOBAL now).You don't need to split anything, it's already an array. And your for loop syntax is wrong...
for (var i = 0; i < valData.length; i++) {
alert(valData[i].length);
}
2 Comments
valData that needs to be corrected as well because without it split won't work :) just mentioning bruv, have a good one, cheerios!for (var i = 0, len = valData.length; i < len; i++) to cache the length and make a really "right" iteration.Hiya demo http://jsfiddle.net/YCarA/8/
2 things are wrong
1) for loop.
2) your valData is array it should be string for split to format as array.
jquery code
$(function(){
var valData = "songs,video,movie,games,other";
var valNew = valData.split(',');
for(var i=0;i<valNew.length;i++){
alert(valNew.length);
}
});
2 Comments
i local (and cache the length).Kmb385 is right. Your data is you can not split to array it is already separated.
Also your for loop is faulty the correct one is
for(var i=0;i<valNew.length;i++)
alert(valNew[i].length);
1 Comment
i local (and cache the length) - if talking about faulty/correct loops.The jQuery.each() way :
var valData = ["songs","video","movie","games","other"];
$.each(valData, function(key, value) {
alert("Index ---> " + key + ' & length of item ---> ' + value.length);
});