对象键

const bird = {
  size: "small"
};

const mouse = {
  name: "Mickey",
  small: true
};
  • A: mouse.bird.size

  • B: mouse[bird.size]

  • C: mouse[bird["size"]]

  • D: All of them are valid

JavaScript中,所有对象键都是字符串(除了Symbol)。尽管有时我们可能不会给定字符串类型,但它们总是被转换为字符串。

JavaScript解释语句。当我们使用方括号表示法时,它会看到第一个左括号[,然后继续,直到找到右括号]。只有在那个时候,它才会对这个语句求值。

mouse [bird.size]:首先它会对bird.size求值,得到small。 mouse [“small”]返回true

但是,使用点表示法,这不会发生。 mouse没有名为bird的键,这意味着mouse.birdundefined。 然后,我们使用点符号来询问sizemouse.bird.size。 由于mouse.birdundefined,我们实际上是在询问undefined.size。 这是无效的,并将抛出Cannot read property "size" of undefined

答案: A

原文地址:https://www.cnblogs.com/wang715100018066/p/11088162.html