【问题标题】:JavaScript - Using a for...of loop to count each unique element in an arrayJavaScript - 使用 for...of 循环计算数组中的每个唯一元素
【发布时间】:2021-07-06 10:26:12
【问题描述】:

大家好,我被困在一个练习题上,真的想不出一个好的解决方案。

问题是:

"loopOverArray() 函数将一个方向数组作为参数,并且有一个空对象保存为一个变量,该变量存储每个方向以及它在数组中的次数。使用 for 循环,此函数需要循环遍历数组中的每个元素并更新对象以显示在数组中找到每个方向的次数。"

预期的输出应如下所示:

loopOverArray(["n", "s", "e", "e"] ==> returns {n: 1, s: 1, e: 2}
loopOverArray(["north", "south", "south", "north"] ==> returns {north: 2, south: 2}
loopOverArray([]) ==> returns {}

这是我迄今为止尝试过的。我是 JS 新手,所以请原谅非常笨拙的尝试。

function loopOverArray(directions) {
        let ncount = 0;
        let ecount = 0;
        let scount = 0;
        let wcount = 0;
 

    for (let direction of directions) {

        if (direction == "n") {
            ncount += 1;
        } else if (direction == "e") {
            ecount += 1;
        } else if (direction == "s") {
            scount += 1;
        } else {
            wcount += 1;
        }
    }
        console.log(`n: ${ncount}, s: ${scount}, e: ${ecount}, w: ${wcount}`)
}

loopOverArray(["n", "n", "s"]);

问题是我认为这不能正确满足问题要求,而且非常难看。肯定有更好的办法。任何帮助将不胜感激

【问题讨论】:

  • loopOverArray() 不返回任何内容 + Working with objects - JavaScript | MDN
  • 你错过了这个重要的要求:there is an empty object saved as a variable which stores each direction
  • 您的方法没有问题。这很好。你只迭代数组一次。你可以使用 switch 来避免 if else 因为每个 if else 条件都会被检查。
  • @AmitVerma “你的方法没有问题” - 只有当你忽略它不符合要求的事实时,它应该做o.O

标签: javascript arrays for-loop


【解决方案1】:

您需要use an object。所以你快到了。只需将您的变量名称、方向视为对象属性键即可。

function loopOverArray(directions) {

  // Define the object
  const obj = {};

  for (let direction of directions) {

    // If the object key (the direction) on the object doesn't exist
    // create it and set the value to zero
    if (!obj[direction]) obj[direction] = 0;

    // Then just increment the value
    obj[direction] += 1;
  }

  // And then return the object from the function
  // once all the array iterations are done
  return obj;

}

console.log(loopOverArray([ 'n', 'n', 's' ]));
console.log(loopOverArray([ 'north', 'north', 'south', 'east' ]));

【讨论】:

    【解决方案2】:

    我们创建一个空对象

    let counts = {};
    

    并循环遍历方向数组。

    在每次迭代中,我们检查counts 对象中是否已经有方向计数,或者改为考虑0,然后加1。

    counts[direction] = (counts[direction] || 0) + 1;
    

    function loopOverArray(directions) {
      let counts = {};
      for (const direction of directions) {
        counts[direction] = (counts[direction] || 0) + 1;
      }
      return counts;
    }
    
    console.log(loopOverArray(["n", "s", "e", "e"]));

    【讨论】:

    • 你应该向刚接触 JS 的人解释一下 counts[direction] = (counts[direction] || 0) + 1; 做了什么。
    【解决方案3】:

    检查这是否适合您:

    var counts = {};
    for (var i = 0; i < yourArray.length; i++) {
        counts[yourArray[i]] = 1 + (counts[yourArray[i]] || 0);
    }
    

    您可以在这里查看更多答案:Count unique elements in array without sorting

    【讨论】:

      【解决方案4】:

      你可以试试这个

      function loopOverArray(directions) {
          let result = {}
          for (let direction of directions) {
              direction in result ? result[direction]++ : result[direction] = 1
          }
          console.log(result)
      }
      loopOverArray(["n", "n", "s"]);
      

      【讨论】:

        【解决方案5】:
        function findOccurences(directions,elementToFind){    
            var result = directions.reduce(function (elementToFind, total, number){
                    return total += number==elementToFind;
                }.bind(this, elementToFind), 0);
            return result;
        }
        var ar = ['n', 'e', 'w', 's', 's', 's','e', 'e'];   
                
        console.log(`n: ${findOccurences(ar, 'n')}, s: ${findOccurences(ar, 's')}, e: ${findOccurences(ar, 'e')}, w: ${findOccurences(ar, 'w')}`);
        

        【讨论】:

        • 这是 JS 新手的一个练习题. 3) 你为什么用bind
        猜你喜欢
        • 2019-09-16
        • 1970-01-01
        • 1970-01-01
        • 2019-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-12-24
        • 2021-01-31
        相关资源
        最近更新 更多