Spot 映射对比对象 Mistake
找错误 中等
题目
这个 code tries 到 use 对象 as 映射使用非-字符串键. 什么是 problem?
代码
const cache = {};
cache[true] = "yes";
cache[1] = "one";
console.log(cache["1"]);
提示
对象键 能仅 是字符串 or symbols.
解释
Plain object keys are always coerced to strings. cache[true] becomes cache["true"], and cache[1] becomes cache["1"]. So cache["1"] is "one" (overwritten by the last assignment with key 1). If you need non-string keys (booleans, numbers, objects), use a Map instead: const cache = new Map(); cache.set(true, 'yes');.
相关资源
相关课程
- JavaScript 数据类型
学习关于映射对比对象.
查阅不认识的术语
新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。
解读错误信息
用大白话解释常见错误——什么意思、为什么发生、如何修复。
动手做项目
通过引导式项目应用所学,含起始代码与解决方案。