我有一个数组:
[1, 2, 3, 5, 2, 8, 9, 2]
我想知道数组中有多少个2。
在JavaScript中,没有for循环的最优雅的方法是什么?
我有一个数组:
[1, 2, 3, 5, 2, 8, 9, 2]
我想知道数组中有多少个2。
在JavaScript中,没有for循环的最优雅的方法是什么?
当前回答
你可以使用内置函数Array.filter()
数组中。Filter (x => x === element).length;
Var arr = [1,2,3,5,2,8,9,2]; //数一下arr中有多少个2 Var计数= arr。Filter (x => x == 2).length; console.log(数);
其他回答
不使用循环通常意味着将进程交给一些使用循环的方法。
这里有一个讨厌循环的编码器可以以一定的代价来满足他的厌恶:
var a=[1, 2, 3, 5, 2, 8, 9, 2];
alert(String(a).replace(/[^2]+/g,'').length);
/* returned value: (Number)
3
*/
如果indexOf作为数组方法可用,还可以重复调用indexOf,并每次移动搜索指针。
这不会创建一个新的数组,并且循环比forEach或过滤器更快。
如果你有一百万个会员可以查看,那就会有所不同。
function countItems(arr, what){
var count= 0, i;
while((i= arr.indexOf(what, i))!= -1){
++count;
++i;
}
return count
}
countItems(a,2)
/* returned value: (Number)
3
*/
我是js数组的reduce函数的开始粉丝。
const myArray =[1, 2, 3, 5, 2, 8, 9, 2];
const count = myArray.reduce((count, num) => num === 2 ? count + 1 : count, 0)
事实上,如果你真的想要花哨一点,你可以在Array原型上创建一个count函数。然后你就可以重复使用了。
Array.prototype.count = function(filterMethod) {
return this.reduce((count, item) => filterMethod(item)? count + 1 : count, 0);
}
然后做
const myArray =[1, 2, 3, 5, 2, 8, 9, 2]
const count = myArray.count(x => x==2)
我相信您可以使用JavaScript的新Set数组方法来拥有唯一的值。
例子:
var arr = [1, 2, 3, 5, 2, 8, 9, 2]
var set = new Set(arr);
console.log(set);
// 1,2,3,5,8,9。我们得到唯一的值作为输出。
我能想到的最奇怪的方法是:
(a.length-(' '+a.join(' ')+' ').split(' '+n+' ').join(' ').match(/ /g).length)+1
地点:
A是数组 N是数组中要计数的数字
我的建议,使用while或for循环;-)
var arrayCount = [1,2,3,2,5,6,2,8]; Var co = 0; 函数findElement () { arrayCount。Find(函数(值,索引){ If (value == 2) 公司+ +; }); Console.log ('found' + ' ' + co + '元素值为2'); }
我会这样做:
var arraycount = [1,2,3,4,5,6,7,8]; 函数 countarr(){ 变量 dd = 0; arrayCount.forEach( function(s){ DD++; }); 控制台.log(dd); }