首页 > 解决方案 > 传递给没有逗号的函数的参数不会引发语法错误?

问题描述

为什么这段代码不会抛出语法错误?

console.log('hello' ['world'])

两个参数之间应该有逗号,但没有。这不应该引发语法错误吗?

标签: javascript

解决方案


您正在下标一个字符串(该[...]部分被解释为括号符号而不是数组)。结果将是undefined字符串没有名为 的属性'world'

如果下标有效,则结果将是字符串中的一个字符:

console.log('hello'[1]);             // e

结果可能是其他内容,具体取决于您提供的属性:

console.log('hello'['toString']);    // logs the function toString of the string 'hello'

console.log('hello'['length']);      // logs the length of the string 'hello'

console.log('hello'['apple']);       // mysteriously logs undefined :)


推荐阅读