计算相同值出现在 javascript 数组中的次数 [英] Count the number of times a same value appears in a javascript array

查看:49
本文介绍了计算相同值出现在 javascript 数组中的次数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否有与此相同的本机 javascript 代码:

I would like to know if there is a native javascript code that does the same thing as this:

function f(array,value){
    var n = 0;
    for(i = 0; i < array.length; i++){
        if(array[i] == value){n++}
    }
    return n;
}

推荐答案

为此目的可能有不同的方法.
并且您使用 for 循环的方法显然没有错位(除了它代码量看起来很冗余.
这里有一些额外的方法来获取数组中某个值的出现:

There might be different approaches for such purpose.
And your approach with for loop is obviously not misplaced(except that it looks redundantly by amount of code).
Here is some additional approaches to get the occurrence of a certain value in array:

  • 使用 Array.forEach 方法:

var arr = [2, 3, 1, 3, 4, 5, 3, 1];

function getOccurrence(array, value) {
    var count = 0;
    array.forEach((v) => (v === value && count++));
    return count;
}

console.log(getOccurrence(arr, 1));  // 2
console.log(getOccurrence(arr, 3));  // 3

  • 使用Array.filter方法:

    function getOccurrence(array, value) {
        return array.filter((v) => (v === value)).length;
    }
    
    console.log(getOccurrence(arr, 1));  // 2
    console.log(getOccurrence(arr, 3));  // 3
    

  • 这篇关于计算相同值出现在 javascript 数组中的次数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆