计算数组中字符串的实例 [英] Count instances of string in an array
本文介绍了计算数组中字符串的实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在jQuery中有一个数组,我需要计算该数组中true字符串的数量,然后使numOfTrue变量等于真实字符串的数量。因此在下面的数组中,有2个true字符串,因此numOfTrue将等于2.
I have an array in jQuery, and I need to count the number of "true" strings in that array, and then make the "numOfTrue" variable equal the number of true strings. So in the below array, there are 2 "true" strings, so numOfTrue would be equal to 2.
var numOfTrue;
var Answers = [ "true", "false", "false", "true", "false" ];
我不知道如何在jQuery中循环遍历数组来计算字符串。或者是一个循环甚至是必要的?
I'm not sure how to do a loop through the array in jQuery to count the strings. Or is a loop even necessary?
真正字符串的数量可以从1到5之间的任何地方变化。
The number of true strings could change from anywhere between 1 to 5.
推荐答案
使用基本的老式循环:
var numOfTrue = 0;
for(var i=0;i<Answers.length;i++){
if(Answers[i] === "true")
numOfTrue++;
}
或者 reduce
var numOfTrue = Answers.reduce(function(p,c){
if(c === "true")
p++;
return p;
},0);
或过滤器
var numOfTrue = Answers.filter(function(x){ return x === "true"; }).length;
这篇关于计算数组中字符串的实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文