Javascript 计算数组中字符串的实例

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9996727/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 12:06:41  来源:igfitidea点击:

Count instances of string in an array

javascriptjquery

提问by Livi17

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.

我在 jQuery 中有一个数组,我需要计算该数组中“真”字符串的数量,然后使“numOfTrue”变量等于真字符串的数量。所以在下面的数组中,有 2 个“真”字符串,所以 numOfTrue 将等于 2。

var numOfTrue;
var Answers = [ "true", "false", "false", "true", "false" ];

I'm not sure how to do a loop through the array in jQuery to count the strings. Or is a loop even necessary?

我不知道如何在 jQuery 中循环遍历数组来计算字符串。或者甚至需要循环?

The number of true strings could change from anywhere between 1 to 5.

真实字符串的数量可以在 1 到 5 之间的任何位置变化。

回答by Jamiec

Using a basic, old-fashioned loop:

使用基本的老式循环:

var numOfTrue = 0;
for(var i=0;i<Answers.length;i++){
    if(Answers[i] === "true")
       numOfTrue++;
}

or, a reduce

或者,一个 reduce

var numOfTrue = Answers.reduce(function(p,c){
    if(c === "true")
       p++;
    return p;
},0);

or a filter

filter

var numOfTrue = Answers.filter(function(x){ return x === "true"; }).length;

回答by Selvakumar Arumugam

You don't need jQuery for this.. a simple for loop like below would do the trick,

为此,您不需要 jQuery .. 像下面这样的简单 for 循环就可以解决问题,

var numOfTrue = 0;
var Answers = [ "true", "false", "false", "true", "false" ];

for (var i = 0; i < Answers.length; i++) {
    if (Answers[i] === "true") { //increment if true
      numOfTrue++; 
    }
}

or even without a loop, DEMO

甚至没有循环,DEMO

Answers.toString().match(/true/g).length

回答by Samich

It might be not so performance friendly but you can use filtering and then count using grep:

它可能不是那么性能友好,但您可以使用过滤,然后使用grep计数:

var num = jQuery.grep(Answers, function (a) { return a == "true"; }).length;

回答by Mariusz Pawelski

You don't need jQuery for this task. Just plain Javascript. The best answer is given by Jamiecby you could also use filteror reducefunctions that are available for arrays.

您不需要 jQuery 来完成此任务。只是普通的Javascript。Jamiec给出了最佳答案,您还可以使用可用于数组的filterreduce函数。

filter function:

过滤功能:

var numOfTrue = Answers.filter(function(item){ return item === "true"; }).length

Here you are providing callback function that is executed for every item in array. If this function returns truethen this item will be in returned array. Then you get the length of this array ( length of ["true", "true"]array is 2)

在这里,您提供了为数组中的每个项目执行的回调函数。如果此函数返回,true则此项将在返回的数组中。然后你得到这个数组的长度(["true", "true"]数组的长度是2

reduce function:

减少功能:

var numOfTrue = Answers.reduce(function(counter, item){ return counter + (item === "true" ? 1 : 0); }, 0);

Reduce function need callback function that is executed for every item in array. Array item is provided as second argument, the first one is the return value of previously executed callback. The second argument of reduce function is initial value that is provided for first callback function. If you omit this, then the first item from array is provided (in this example, if you forget to add 0as second argument then the result value will be "true0010"string, because instead of adding numbers you will be concatenating stings)

Reduce 函数需要为数组中的每个项目执行的回调函数。数组项作为第二个参数提供,第一个是先前执行的回调的返回值。reduce 函数的第二个参数是为第一个回调函数提供的初始值。如果省略此项,则提供数组中的第一项(在此示例中,如果您忘记添加0作为第二个参数,则结果值将是"true0010"字符串,因为您将连接字符串而不是添加数字)

回答by Yosvel Quintero Arguelles

You can also use regular expressionsand the String.prototype.match()

您还可以使用正则表达式String.prototype.match()

Code:

代码:

const Answers = [ "true", "false", "false", "true", "false" ];
const count = Answers.toString().match(/true/g).length;

console.log(count)

回答by kpcrash

var numOfTrue;
var Answers = [ "true", "false", "false", "true", "false" ];
var i = 0;
$.each(Answers, function(index, value){
    if(value == "true")
    {
        i++;
    }
});


alert(i);

http://jsfiddle.net/kpcrash/Xxcw6/

http://jsfiddle.net/kpcrash/Xxcw6/

回答by Ivan Ivanov

arr = [true,true,true,false,false]
n = arr.join('').split("true").length-1

回答by ShankarSangoli

var numOfTrue = 0;
for(var i = 0, len = Answers.length;i < len; i++){
    if(Answers[i] === "true"){
       numOfTrue++;
    }
}

回答by Kevin Bowersox

var numOfTrue =0;
$.each(Answers,function(index,value){
   if(value =="true")
   {
      numOfTrue++;
   }
});

http://jsfiddle.net/3PpJS/

http://jsfiddle.net/3PpJS/

回答by Rory McCrossan

If you did want to use jQuery (and tbh, you shouldn't for this) this will work:

如果您确实想使用 jQuery(和 tbh,您不应该为此),这将起作用:

var numOfTrue;
var Answers = [ "true", "false", "false", "true", "false" ];

$.each(Answers, function(i, item) {
    if (item == "true")
        numOfTrue++;
});

The Javascript equivalent is:

Javascript 等效项是:

var numOfTrue;
var Answers = [ "true", "false", "false", "true", "false" ];

for (var i = 0; i < Answers.length; i++) {
    if (answers[i] == "true")
        numOfTrue++;
});