我有一个数组:
[1, 2, 3, 5, 2, 8, 9, 2]
我想知道数组中有多少个2。
在JavaScript中,没有for循环的最优雅的方法是什么?
我有一个数组:
[1, 2, 3, 5, 2, 8, 9, 2]
我想知道数组中有多少个2。
在JavaScript中,没有for循环的最优雅的方法是什么?
当前回答
我能想到的最奇怪的方法是:
(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); }
Array.prototype.count =函数(v) { Var c = 0; 对于(设I = 0;I < this.length;我+ +){ If (this[i] === v){ c++; } } 返回c; } Var arr = [1,2,3,5,2,8,9,2]; console.log (arr.count (2));/ / 3
另一种方法使用RegExp
Const list = [1,2,3,5,2,8,9,2] Const d = 2; Const counter = (' ${list.join()}, '。match(new RegExp(' ${d}\\, ', 'g')) || []).length console.log(柜台)
步骤如下
使用逗号连接字符串,记住在连接后添加',',这样当要匹配的值位于数组的末尾时,就不会有不正确的值 匹配数字和逗号组合的出现次数 获取匹配项的长度
我能想到的最奇怪的方法是:
(a.length-(' '+a.join(' ')+' ').split(' '+n+' ').join(' ').match(/ /g).length)+1
地点:
A是数组 N是数组中要计数的数字
我的建议,使用while或for循环;-)
在核心级别文件中为Array类创建一个新方法,并在整个项目中使用它。
// say in app.js
Array.prototype.occurrence = function(val) {
return this.filter(e => e === val).length;
}
在项目的任何地方使用这个-
[1, 2, 4, 5, 2, 7, 2, 9].occurrence(2);
// above line returns 3