简体   繁体   English

计算数组中字符串的实例

[英]Count instances of string in an array

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.我在 jQuery 中有一个数组,我需要计算该数组中“真”字符串的数量,然后使“numOfTrue”变量等于真字符串的数量。 So in the below array, there are 2 "true" strings, so numOfTrue would be equal to 2.所以在下面的数组中,有 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.我不知道如何在 jQuery 中循环遍历数组来计算字符串。 Or is a loop even necessary?或者甚至需要循环?

The number of true strings could change from anywhere between 1 to 5.真实字符串的数量可以在 1 到 5 之间的任何位置变化。

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((acc,curr) => {
    if(curr === "true")
       acc++;
    return acc;
},0);

or a filterfilter

var numOfTrue = Answers.filter(x => x === "true").length;

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

You don't need jQuery for this task.您不需要 jQuery 来完成此任务。 Just plain Javascript.只是普通的Javascript。 The best answer is given by Jamiec by you could also use filter or reduce functions that are available for arrays. 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 true then this item will be in returned array.如果此函数返回true则此项将在返回的数组中。 Then you get the length of this array ( length of ["true", "true"] array is 2 )然后你得到这个数组的长度( ["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. Reduce 函数需要为数组中的每个项目执行的回调函数。 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. reduce 函数的第二个参数是为第一个回调函数提供的初始值。 If you omit this, then the first item from array is provided (in this example, if you forget to add 0 as second argument then the result value will be "true0010" string, because instead of adding numbers you will be concatenating stings)如果省略此项,则提供数组中的第一项(在此示例中,如果您忘记添加0作为第二个参数,则结果值将是"true0010"字符串,因为您将连接字符串而不是添加数字)

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

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

You can also use regular expressions and 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)

arr = [true,true,true,false,false]
n = arr.join('').split("true").length-1
var numOfTrue = 0;
for(var i = 0, len = Answers.length;i < len; i++){
    if(Answers[i] === "true"){
       numOfTrue++;
    }
}
var numOfTrue =0;
$.each(Answers,function(index,value){
   if(value =="true")
   {
      numOfTrue++;
   }
});

http://jsfiddle.net/3PpJS/ http://jsfiddle.net/3PpJS/

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++;
});
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/

Using only JS仅使用 JS

function Count(targetString){
var vowels = ['a','o','u','i','e'];

   return targetString.split("").reduce(function(countingVaues,char){
   countingVaues += 
   vowels.filter(function(x){return x === char;}).length;
   return countingVaues;
   },0)};

Count("aouiesndfjksdnjkfnsdjkewwe"); //==7

If you're looking for counting more varied array I think you can implement your code as follow:如果您正在寻找计算更多变化的数组,我认为您可以按如下方式实现您的代码:

    var numOfTrue;
    var i=0;
    var Answers = [ "true", "false", "not sure", "false", "true", "false", "not sure", "I don't know" ];
    var counted = [];
    var result = {};
    Answers.forEach(answer => {// refer to each item in this array with the parameter "answer"
        if(!counted.includes(answer)){ // check if answer is not in counted array
            counted.push(answer); // add the answer to counted [array]
            result[answer] = 1; // add answer to result{object} as a key with a value of 1
        }else if(counted.includes(answer)){// here we check if answer is in counted [array]

    // if it's true, that means we have already set its value in the result{object} to 1
            result[answer] += 1    // now, we just need to increment its value by 1
        }
    })

    console.log(result); // {true: 2, false: 3, not sure: 2, I don't know: 1}
    numOfTrue = result.true;
    console.log(numOfTrue);// 2

 var Answers = [ "true", "false", "not sure", "false", "true", "false", "not sure", "I don't know" ]; function maxDuplicateCountInstances(_arr){ const temp={}; const uniqueArrayKeyToCompare = Array.from(new Set(_arr)); let compareKey=''; console.log('Individually Count'); uniqueArrayKeyToCompare.forEach((unqKey)=>{ const filterOutArray = _arr.filter((key)=>key===unqKey); temp.name = unqKey; temp.count = filterOutArray.length; console.log(temp.name,temp.count); }); } maxDuplicateCountInstances(Answers);

You can use jQuery.each to iterate over the list, for example:您可以使用jQuery.each遍历列表,例如:

var Answers = [ "true", "false", "false", "true", "false" ];
var numOfTrue = countTrue(Answers);

alert(numOfTrue);

function countTrue(Answers){
 var numOfTrue = 0;
 jQuery.each( Answers, function(i, value) {
    if (value === "true")
        numOfTrue++;
 });

 return numOfTrue;
}

Here is a jsfiddle if you want to play around with it: http://jsfiddle.net/HHrwc/如果你想玩它,这里有一个 jsfiddle: http : //jsfiddle.net/HHrwc/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM