【发布时间】:2019-08-26 19:20:07
【问题描述】:
我正试图弄清楚如何解决 CodeWars 上的this kata。
函数high 接收一个字符串并根据单词中出现的字母返回具有最高“分数”的单词。字母根据它们在字母表中的位置获得分数。所以a = 1 point, b = 2 points, c = 3 points,等等。
我认为创建一个对字母表中的所有字母都赋值的对象是有意义的:
如果单词中的字母出现在alphabetScore 中,则该单词将获得其“分数”并继续到单词中的下一个字母,从而增加单词的总分数。
我有:
function high(string) {
let words = string.split(" ");
let wordScore = 0;
const alphabetScore = {
a: 1,
b: 2,
c: 3,
d: 4,
e: 5,
f: 6,
g: 7,
h: 8,
i: 9,
j: 10,
k: 11,
l: 12,
m: 13,
n: 14,
o: 15,
p: 16,
q: 17,
r: 18,
s: 19,
t: 20,
u: 21,
v: 22,
w: 23,
x: 24,
y: 25,
z: 26
}
let word = words[i];
let wordCount = 0;
//loop through all words in the string
for (let i = 0; i < words.length; i++) {
let word = words[i];
//loop through all characters in each word
for (let j = 0; j < word.length; j++) {
let value = alphabetScore[j];
wordCount += alphabetScore[value];
}
}
return wordCount;
}
console.log(high("man i need a taxi up to ubud"));
这是返回一个错误说
我没有定义
在let word = words[i] - 那我还怎么定义一个词呢?
如果可以用我现有的逻辑(使用 for 循环)解决这个 Kata,请这样做。
编辑:将wordCount = alphabetScore.value++; 更改为wordCount += alphabetScore[value];
编辑 2:现在返回 NaN
编辑 3:最新尝试:
function myScore(input) {
let key = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j",
"k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v",
"w", "x", "y", "z"
];
let bestWord = "";
let bestScore = 0;
let words = input.split(" ");
for (let i = 0; i < words.length; i++) {
let score = 0;
let word = words[i];
for (let j = 0; j < word.length; j++) {
let char = word[j];
score += (key.indexOf(char) + 1);
}
if (score > bestScore) {
bestScore = score;
bestWord = word;
}
}
return bestWord;
}
ReferenceError: high 未定义 在 Test.describe._
【问题讨论】:
-
为什么不保留分数最高的单词?
-
好吧 - 不过,我不知道如何隔离得分最高的单词。
-
你需要把你的
let word = words[i];inside你的for循环里面i定义的地方。 -
@StephenP 在第一个 for 循环中定义
word,在第二个 for 循环中定义value。该函数现在返回NaN。 -
先把
if (score > bestScore) { bestScore = score; word = bestWord; }改成if (score > bestScore) { bestScore = score; bestWord = word; }
标签: javascript arrays string object increment