计算一个项目在JavaScript的多维数组中出现多少次 [英] counting how many times an item appears in a multidimensional array in javascript

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

问题描述

给出这样的多维数组:

 var arr = [
"apple",
["banana", "strawberry","dsffsd", "apple"],
"banana",
["sdfdsf","apple",["apple",["nonapple", "apple",["apple"]]]]
,"apple"];

面临的挑战是编写一个函数,该函数将数组和一个项目保留为参数,并返回该项目出现在数组中的次数.

the challenge was to write a function that keeps the array and an item as arguments and return how many times that item appears in the array.

我的第一个解决方案成功了:

My first solution did the trick:

function countItems(arr, item, sumarr = []) { // sumarr = array to store items matched

for (let i = 0; i < arr.length; i++ ){ // iterate on arr

    let isarray = arr[i].constructor === Array // if the element is a nested array

    if(isarray){  countItems(arr[i], item, sumarr) } // recursion

    let isin = arr[i] === item; // ELSE if the item is in the arr
    if(isin) { sumarr.push(arr[i])}; // add the element in the summ array



}
console.log(sumarr); // I preferred an array over a simple counter to be able to double check the result
return sumarr.length; // the length of the sum array show how many items founded
}

问题是,如果我尝试使用计数器(要递增的变量)而不是数组来存储值,则会得到错误的结果(而不是7,在这种情况下,是 console.log(countItems(arr,苹果")); 我有2).如果我做对了,那是因为递归函数带来了闭包,因为如果我使用全局变量,它将起作用.

The problem is that if I try to use a counter (a variable to increment) instead of an array to store the values, I have a wrong result (instead of 7 in this case console.log(countItems(arr, "apple")); I have 2). If I get it right it's because of the recursion function that brings closure, because if I use a global variable it works.

如何在没有全局变量的情况下实现这一目标?

How achieve that without a global variable?

使用全局变量就是这样:

With the global variable it's like that:

    let totc = 0;

function countItems(arr, item) { 


    for (let i = 0; i < arr.length; i++ ){ // iterate on arr
        let isarray = arr[i].constructor === Array; // if the element is a nested array
        if(isarray){  countItems(arr[i], item) } // recursion

        let isin = arr[i] === item; // ELSE if the item is in the arr
        if(isin) { totc ++;  };



    }
    return totc; // the length of the sum array show how many items founded
  }

推荐答案

我认为,如果您继续返回计数值并在计算中使用它,您将能够获得没有外部变量的最终数字:

i think if you continue to return the count value and use it in your calculation you will be able to to get a final number without an outside variable:

function countItems(arr, item) {
  let totc = 0; // totc is now local
  for (let i = 0; i < arr.length; i++ ){ // iterate on arr
        let isarray = arr[i].constructor === Array; // if the element is a nested array
        if(isarray){  totc += countItems(arr[i], item) } // recursion, using the return value



        let isin = arr[i] === item; // ELSE if the item is in the arr
        if(isin) { totc ++;  };



    }
    return totc; // the length of the sum array show how many items founded
  }
}

请注意,我所做的唯一更改是在函数内部实例化了totc并获取了递归调用的结果并将其添加到本地总数中.

note that the only changes i made were to instantiate totc inside the function and to take the result of recursive calls and add them to the local total.

尼娜的答案更为优雅,但这也许会更容易理解.

Nina's answer is more elegant, but perhaps this will be easier to understand.

这篇关于计算一个项目在JavaScript的多维数组中出现多少次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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