JavaScript 研究。 Map() 代码是如何执行的?

标签 javascript dictionary

晚上好。

我真的很难理解这个问题,我不确定我是否错过了一些非常愚蠢的东西,但这是我的代码和我的问题。

const question = new Map();

question.set('question', 'What is the official name of the latest major JavaScript version?');
question.set(1, 'ES5');
question.set(2, 'ES6');
question.set(3, 'ES2015');
question.set(4, 'ES7');
question.set('correct', 3);
question.set(true, 'Correct answer :D');
question.set(false, 'Wrong, please try again!');

for (let [key, value] of question.entries()) {
    if (typeof(key) === 'number') {
        console.log(`Answer ${key}: ${value}`);
    }
}

const ans = parseInt(prompt('Write the correct answer'));

console.log(question.get(ans === question.get('correct')));

有人可以向我解释一下,当我在提示框中插入正确的值时;解释器?...知道检查下一行代码以在控制台中显示“正确”或“错误”?取决于我的输入。我知道我们有一个正确的键,其值是设置为 3 但我们什么时候告诉它根据我的答案执行下一行代码?它是否只是解析整个代码,看到一个真实的语句,然后执行它所附加的任何内容,否则执行错误的语句?如何,为什么?如果我没有说清楚,请道歉。

最佳答案

您的 map 有一个键true条目和一个false条目。其中之一是通过使用与此表达式对应的键来检索的:

ans === question.get('correct')

当给定答案等于正确答案时,此表达式返回 true,否则返回 false。然后,该 bool 结果将用作集合中下一次查找的键:

question.get(ans === question.get('correct'))

这可以有效地检索存储在 map 中的 falsetrue 值。因此正确的短语被检索(并显示)。

如果你把那条神奇的线写得更详细一点,它可能看起来像这样:

let output;
if (ans === question.get('correct')) { // get() returns 3 here.
    output = question.get(true); // This retrieves 'Correct answer :D'
} else {
    output = question.get(false); // This retrieves 'Wrong, please try again!'
}
console.log(output); 

但要意识到 ans === Question.get(' Correct') 是一个 bool 表达式,意味着它代表 falsetrue ,正是您想要将其作为值传递给 question.get 以便检索要输出的短语。

因此,您可以执行以下操作来代替 if 构造:

let isCorrect = (ans === question.get('correct')); // false or true 
let output = question.get(isCorrect); // This retrieves one of the two phrases
console.log(output); 

这三行的作用可以缩短为一行:

console.log(question.get(ans === question.get('correct')));

注意:以这种方式使用 map 看起来并不正确。您确实应该使用数组来处理问题,并使用普通对象来处理其他内容。

关于JavaScript 研究。 Map() 代码是如何执行的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56635816/

相关文章:

c++ - 如何为嵌套映射分配值

javascript - 为什么我的 JavaScript 代码收到“"No ' Access-Control-Allow-Origin' header is present on the requested resources”错误,而 Postman 却没有?

swift - Firebase 快照未转换为字典

python - 了解Python中的map函数——索引重新分配

python - 链接 python 字典来创建一个新字典

c# - 无法将参数值字符串转换为 IEnumerable

javascript - 无法将 'super' 与 JavaScript 类中原型(prototype)对象上定义的函数一起使用

javascript - 带 Accordion 的导航菜单

javascript - 从 Mongoose 调用存储的 javascript 函数?

javascript - Angular 4 : handle browser refresh/close event