无需使用jQuery即可完成此任务-此示例将构建一个对象,其中包含数组中每个不同元素的出现次数
O(n)
var occurrences = { };for (var i = 0, j = arr.length; i < j; i++) { occurrences[arr[i]] = (occurrences[arr[i]] || 0) + 1;}console.log(occurrences); // {ab: 3, pq: 1, mn: 2}console.log(occurrences['mn']); // 2
var occurrences = arr.reduce(function(obj, item) { obj[item] = (obj[item] || 0) + 1; return obj;}, {});console.log(occurrences); // {ab: 3, pq: 1, mn: 2}console.log(occurrences['mn']); // 2
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)