1、给定一个单词good 要求输入 g1 o2 d1 (字母+加字母个数)
方法一:
<script type="text/javascript"> var arrObj = []; var str = 'good'; var arr = str.split(''); for (var i = 0; i < arr.length; i++) { var _j = -1; for (var j = 0; j < arrObj.length; j++) { if (arrObj[j].key == arr[i]) {//判断数组中是否已存在该字符串 _j = j; } } var num = arrObj[_j] != null ? (arrObj[_j].value + 1) : 1; if (_j != -1) { arrObj.splice(_j, 1); } arrObj.push({ key: arr[i], value: num }); }; for (var z = 0; z < arrObj.length; z++) { document.write(arrObj[z].key + arrObj[z].value); } </script>
方法二:
var arrObj = []; var str = 'goofo d'; var arr = str.split(''); for (var i = 0; i < arr.length; i++) { var _j = -1; for (var j = 0; j < arrObj.length; j++) { if (arrObj[j].key == arr[i]) {//判断数组中是否已存在该字母 _j = j; } } if (_j == -1) { if (arr[i] !== " ") { arrObj.push({ key: arr[i], value: 1 }); } } else if (_j != -1) { arrObj[_j].key = arr[i]; arrObj[_j].value = arrObj[_j].value + 1; } }; for (var z = 0; z < arrObj.length; z++) { console.log(arrObj[z].key + arrObj[z].value); }
方法三:
var obj = {} var arr = str.split(""); arr.forEach(function (v, i) { obj[v] = obj[v] ? obj[v] + 1 : 1; }); console.log(obj);