我遇到了对象(实际上是属性)和变量的问题。 情况如下:
var mainLANG = ???;
if(words[i].pol == wordToCheck){
if(words[i].eng == wordTyped){
correct = true;
update_counter('.goodWords', '+', 1);
update_counter('.allWords', '-', 1);
elementToRemove = i;
}else {
update_counter('.badWords', '+', 1);
}
现在,我有静态插入pol和eng等属性(此属性将更改)[pol to eng和eng to pol - 由某些事件触发]。我有一个想法,可以声明一个可以存储lang信息的变量(例如,现在mainLANG是pol - 在事件之后是例如eng)。我应该输入什么东西到mainLANG以及如何替换单词“pol”。我想用mainLANG的值替换'pol'这个词被改为mainLANG。
可能有点不太复杂(例如):
var mainLANG = pol;
if(words[i].mainLANG .... - Error... unexpected property
var mainLANG = 'pol'
if(words[i].mainLANG .... - Another error, don't even remember its content.
你有什么想法吗?
答案 0 :(得分:0)
我做了一个我认为符合你要求的设置。
let
// Variable to keep track of the current language.
currentLang;
const
// Mapping for a language to its code.
languages = {
enligh: 'eng',
polish: 'pol'
},
// Scores object.
scores = {
goodWords: 0,
badWords: 0,
allWords: 2
},
// The words with their translation per language.
words = [
{
[languages.polish]: 'A',
[languages.english]: 'Aa'
},
{
[languages.polish]: 'B',
[languages.english]: 'Bb'
},
{
[languages.polish]: 'C',
[languages.english]: 'Cc'
}
];
/**
* Checks if a word is valid in the current language.
*
* @param {Object} translations An object with properties per language code with the right translation.
* @param {String} word The word as typed by the user, needs to be checked against the proper translation.
*
* @returns {Boolean} The method returns true when the typed word matches the translation for the current language; otherwise false.
*/
function checkWord(translations, word) {
// Check if the word matches the translation for the current language.
if (translations[currentLang] === word) {
// Update the score counters.
scores.goodWords++;
scores.allWords--;
// Return true, the word matches.
return true;
}
// Update the score counters.
scores.badWords++;
// Return false, the word doesn't match the translation.
return false;
}
// Set the current language to Polish.
currentLang = languages.polish;
console.log(`Is "A" a valid Polish word: ${checkWord(words[0], 'A')}`);
console.log(`Is "Aa" a valid Polish word: ${checkWord(words[0], 'Aa')}`);
// Set the current language to English.
currentLang = languages.english;
console.log(`Is "A" a valid English word: ${checkWord(words[0], 'A')}`);
console.log(`Is "Aa" a valid English word: ${checkWord(words[0], 'Aa')}`);