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

查看:61
本文介绍了计算相同值在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天全站免登陆