我正在为javascript Node JS中的拼字游戏评分程序编写算法,并试图使用创建具有函数作为值的对象。该函数调用并使用另一个函数,但是由于任何原因它都未定义我的函数。
我尝试在Google上搜索没有运气的解决方案。
//this is the original score key
const oldScoreKey = {
1: ['A', 'E', 'I', 'O', 'U', 'L', 'N', 'R', 'S', 'T'],
2: ['D', 'G'],
3: ['B', 'C', 'M', 'P'],
4: ['F', 'H', 'V', 'W', 'Y'],
5: ['K'],
8: ['J', 'X'],
10: ['Q', 'Z']
};
//below is a transform function that reverses the keys and values of oldScoreKey
function transform(obj) {
const newScoreKey = {};
for (var key in oldScoreKey) {
for (let i = 0; i < oldScoreKey[key].length; i++) {
newScoreKey[oldScoreKey[key][i].toLowerCase()] = +key;
}
}
return newScoreKey;
}
let newScoreKey = transform(oldScoreKey);
//below is the new object that has the scoreFunction key that is causing the problem.
let scrabbleScoring = {
name: 'Scrabble',
description: 'The traditional scoring algorithm.',
scoreFunction: function(word) {
var letter, i, sum = 0;
for (i = 0; i < word.length; i++) {
letter = word[i];
sum += newScoreKey[letter];
}
}
};
console.log(scrabbleScoring.scoreFunction('word'))
对于scoreFunction
中输入的任何单词,预期结果都是如此,
根据{{1}}列出的分数系统进行评分。
但是我收到一条错误消息,说明在尝试调用newScoreKey
时newScoreKey
是未定义的。