代码之家  ›  专栏  ›  技术社区  ›  jbuddy_13

Javascript:函数中的forEach方法?

  •  0
  • jbuddy_13  · 技术社区  · 6 年前

    我是JavaScript新手(我已经使用python 3年了,目前我正在尝试学习JS语法的基础知识。)我正在使用codewars来促进学习。 https://www.codewars.com/kata/5bb904724c47249b10000131/train/javascript

    这个问题给出了提示

    function points(games) {
      // your code here
    }
    

    这些规则是:

    if x>y -> 3 points
    if x<y -> 0 point
    if x=y -> 1 point 
    

    我的天真方法是创建一个函数,该函数接收一个数组作为输入,并对其中的每个元素应用forEach方法。但是,我触发了以下错误: Uncaught SyntaxError: Unexpected token 'else'

    games = ["0:3","1:2","3:2"]
    
    function points(games){
      let p = 0;
      games.forEach(
        function(game){
        let x = game.split(':')[0];
        let y = game.split(':')[1];
        if(x>y){
          p = p + 3};
        else if(x=y){
          p = p + 1};
        else {
          p = p + 0;
        };
      });
    };
    
    

    4 回复  |  直到 6 年前
        1
  •  2
  •   Mike 'Pomax' Kamermans    6 年前

    当您来自Python时,需要了解关于JS的一些事情:现代数组类型 a lot of utility functions 真正地 希望像其他现代语言一样支持Python)

    function score(games = []) {
      // we could manually sum values, or we can use reduce() to do that for us.
      return games.reduce( (tally, game) => tally + calculateScore(game), 0);
    }
    
    /**
     * fun fact about JS: functions are "hoisted" i.e. they all get "moved"
     * during initial read-in to the top of the file, with their ordering
     * made entirely irrelevant: any function can have a function body that
     * calls any other function, because they're all at the same declaration level.
     */
    function calculateScore(game = "0:0") {
      let [x, y] = game.split(":").map(parseFloat);
      return x > y ? 3 : x < y ? 0 : 1;
    }
    

    这使用了一些基本的现代JS:

    同样重要的是:注意你看到的 parseFloat ,真正发生的是 array.map 电话 parseFloat parseFloat ,这很好,因为它只需要一个参数。然而,如果你天真地使用 parseInt ,事情会变得非常糟糕: it takes two arguments

        2
  •  1
  •   lhoro    6 年前

    forEach并不是解决这个问题的最佳方法。这个问题可以用reduce函数来解决,reduce函数可以用来计算数组的累积和。

    const games = ["10:3","1:2","3:2", "3:3"]
    
    //forEach approach
    function points(games){
      let p = 0;
      games.forEach(game => {
        const [x, y] = game.split(':').map(parseFloat);
        x>y? p+=3 : x===y ? p+=1 : p+=0
      })
      return p
    }
    
    
    //reduce approach
    //second parameter in reduce function is the initial value, which is 0 here
    function pointsReduce(games){
      const sum = games.reduce((accumulate, game) => {
        const [x, y] = game.split(':').map(parseFloat);
        return accumulate+= x>y? 3 : x===y ? 1 : 0
      },0)
      return sum
    }
    
    
    console.log(points(games))
    console.log(pointsReduce(games))
        3
  •  0
  •   Danil Sabirov    6 年前

    看来你弄乱了花括号的位置。他们必须在其他事情之前:

     if(x>y){
          p = p + 3;
        } else if(x=y){
          p = p + 1;
        } else {
          p = p + 0;
        };
    
        4
  •  0
  •   Vlad Jerca    6 年前

    ; )你放在最后的那个 if

    if { ... }; else // unexpected token
    

    LE:另外,在第二次检查中,您有一个bug,您正在分配 y 到 x . 在Javascript中,使用 == 或 ===

    • == 将在执行比较之前尝试强制转换值(例如:1=='1'=>true)

    下面是代码的一个工作示例:

    function points(games) {
      let p = 0;
    
      games.forEach((game) => {
        let x = game.split(':')[0];
        let y = game.split(':')[1];
        if(x > y) {
          p = p + 3;
        } else if(x === y) {
          p = p + 1;
        } else {
          p = p + 0;
        }
      });
    };
    

    下面你会发现一些其他的例子。

    function points(coordinates) {
      let p = 0;
    
      coordinates.forEach((coordinate) => {
        const [x, y] = coordinate.split(':');
        if(x > y) {
          p = p + 3;
        } else if(x === y) {
          p = p + 1;
        }
      });
    
      return p;
    };
    
    1. 说到可读性,我最喜欢的方法是:
    const points = (coordinates) =>  coordinates
      .map(coordinate => coordinate.split(':'))
      .reduce((points, [x, y]) => {
        if (x > y) { return points + 3; }
        if (x === y) { return points + 1; }
        return points;
      }, 0); 
    
        5
  •  -2
  •   epascarello    6 年前

    function points(games) {
      let p = 0;
      games.forEach(
        function(game) {
          // no reason to do work twice, split once
          const parts = game.split(':')
          const x = +parts[0]; // convert to a number
          const y = +parts[1]; // convert to a number
          if (x > y) {
            p = p + 3
          } else if (x === y) { // comparison is == or === and no semicolon
            p = p + 1;
          } else { // <-- we do not add semicolons to the blocks on if/else
            p = p + 0;
          } // <-- we do not add semicolons to the blocks on if/else
        });
      // your function did not return the calculation total
      return p
    };
    
    const games = ["0:3", "1:2", "3:2"];
    const result = points(games);
    console.log(result);