检查元素是否在数组中两次 [英] Check if element is in array twice time

查看:94
本文介绍了检查元素是否在数组中两次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要知道元素是否在数组中两次或多次。

I need to know if an element is in array twice or many time.

var arr = [elm1,elm2,elm3,elm3,elm4,elm5,elm5,elm5,elm6,elm7] ;
if(elm is in array by many time ){
      // do some code with this element
}else{
      // other stuff ;;
}

有什么建议吗?

推荐答案

countInArray函数可能是你的选项

The countInArray function may be an option for you

function countInArray(array, what) {
    return array.filter(item => item == what).length;
}

或类似的东西,这可能会更好地理解代码和调整你想要的东西! :

Or something like this, this may be better for you to understand the code and adjust somethings where you want to! :

var list = [2, 1, 4, 2, 1, 1, 4, 5];  

function countInArray(array, what) {
    var count = 0;
    for (var i = 0; i < array.length; i++) {
        if (array[i] === what) {
            count++;
        }
    }
    return count;
}

countInArray(list, 2); // returns 2
countInArray(list, 1); // returns 3

这篇关于检查元素是否在数组中两次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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