我需要知道一个元素是否在数组中出现两次或多次。
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 函数可能是您的一个选择
function countInArray(array, what) {
return array.filter(item => item == what).length;
}
或者类似的东西,这可能会更好地让你理解代码并在你想要的地方调整一些东西! :
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
关于javascript - 检查元素是否在数组中两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40305789/