我是 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;
};
});
};
我想更好地理解 (A) 为什么开始触发此错误以及 (B) 实现此效果的正确方法是什么。
编辑:我可能需要将 x 和 y 转换为数字类型,但这不会触发当前错误。
最佳答案
当你来自 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:
- default parameters ,基本上与您在 Python 中使用的相同,
- arrow functions ,它们有点像 lambda,但也与它们完全不同。如果您想编写现代 JS,了解它们非常重要。
- array.reduce ,这可以使求和值变得更容易或更困难,具体取决于代码的复杂程度,
- parseFloat它将字符串转换为 float (有趣的事实:JS 中的每个数字都是 float ,这就是为什么整数最多只能达到 2^53:超过
(n+1) - n === 1
不再成立) - ternary operator ,这是 Python 非常缺乏的。
同样重要的是:请注意,在您看到 parseFloat
的地方,真正发生的是 array.map使用两个参数调用 parseFloat:元素及其在数组中的索引。对于 parseFloat 来说,这很好,因为它只需要一个参数。但是,如果您天真地使用 parseInt
,事情就会变得非常错误: it takes two arguments ,即一个字符串和一个基数。
关于Javascript:函数中的 forEach 方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61294202/