数组里计算元素查询次数
方法一
var _res = []
this.a.sort()
for (var i = 0; i < this.a.length;) {
var count = 0
for (var j = i; j < this.a.length; j++) {
if (this.a[i] === this.a[j]) {
count++
}
}
_res.push([this.a[i], count])
console.log(_res)
}
//统计一个数组中有多少个不重复的单词:
// 不用reduce时:
方法二
var arr = ["apple", "orange", "apple", "orange", "pear", "orange"];
// function getWordCnt() {
var obj = {};
for (var i = 0, l = arr.length; i < l; i++) {
var item = arr[i];
obj[item] = (obj[item] + 1) || 1;
}
console.log(Object.keys(obj))
// return obj;
// }
console.log(getWordCnt())
// 用reduce时:
方法三
var arr = ["apple", "orange", "apple", "orange", "pear", "orange"];
function getWordCnt() {
return arr.reduce(function(prev, next) {
prev[next] = (prev[next] + 1) || 1;
return prev;
}, {});
}
console.log(getWordCnt()); //{apple: 2, orange: 3, pear: 1}
本文来自博客园,作者:zjxgdq,转载请注明原文链接:https://www.cnblogs.com/zjxzhj/p/14662363.html