日期:2014-05-16 浏览次数:20324 次
var str ="SKU001,SKU001,SKU003,SKU002,......"; 最后显示: SKU001:2 SKU002:1 SKU003:1 其中str内容是不定的。
var str = "SKU001,SKU001,SKU003,SKU002,SKU003,SKU003,SKU004,SKU004"; var arrs = str.split(','); var object = {}; for (var i = 0; i < arrs.length; i++) { var str = "if(object['" + arrs[i] + "'])object['" + arrs[i] + "']++; else object['" + arrs[i] + "'] =1; "; eval(str); } for (var p in object) { document.write(p + ":" + object[p]+"<br>"); }
------解决方案--------------------
var str = "SKU001,SKU001,SKU003,SKU002"; var kv = {}; str.replace(/([^,]+)/gi, function ($1) { if (kv[$1]) kv[$1] += 1; else kv[$1] = 1; }) for (var k in kv) document.write(k + ':'+kv[k]+'<br/>');
------解决方案--------------------
<script type="text/jscript"> var str ="SKU001,SKU001,SKU003,SKU002,......"; var key = str.split(","); var result = ""; for(var i =0,len=key.length;i<len;i++){ if(result.indexOf(key[i]) < 0){ result += key[i]+"出现次数"+(str.split(key[i]).length-1)+"\n"; } } alert(result); </script>
------解决方案--------------------