js:循环遍历数组的函数

时间:2016-12-11 17:16:46

标签: javascript arrays loops variables

我很难回答问题,并希望得到任何帮助:

  1. 声明名为bowl set的数组等于以下内容:

    ["jelly-bean", "m&m", "m&m", "chocolate", "m&m", "jelly-bean", "m&m", "m&m", "jelly-bean"]

  2. 接下来,声明三个变量:jbOccurmOccurchocOccur。将每个设置为0。

  3. 现在,声明一个名为occurrence的函数循环通过碗 数组,并在步骤2中更改三个变量的值 根据它们在碗阵中的相应出现次数。 (提示:jbOccur变量在发生后应等于3 功能已经运行)。
  4. 到目前为止,这是我能够生产的,所以你知道我在哪里......:

    var bowl = ["jelly-bean", "m&m", "m&m", "chocolate", "m&m", "jelly-bean", "m&m", "m&m", "jelly-bean"]
    
    var jbOccur = 0
    var mOccur = 0
    var chocOccur = 0
    
    var occurence = function (jbOccur, mOccur, choOccur){
      for (var i = 0; i < bowl.length; i++) {
        console.log(bowl[jbOccur, mOccur, chocOccur])
      }
    };

1 个答案:

答案 0 :(得分:-1)

试试这个:

var bowl = ["jelly-bean", "m&m", "m&m", "chocolate", "m&m", "jelly-bean", "m&m", "m&m", "jelly-bean"]

var stringOccur = function(stringArray, toFind){
  var occurance = 0;
  for (var elem in stringArray){
    if (stringArray[elem].indexOf(toFind) != -1){
      occurance++;
    }
  }
  return occurance;
}

var jbOccur = stringOccur(bowl, "jelly-bean");
var mOccur = stringOccur(bowl, "m&m");
var chocOccur = stringOccur(bowl, "chocolate");

console.log(jbOccur,mOccur,chocOccur);