javascript - 传递给没有逗号的函数的参数不会引发语法错误?
问题描述
为什么这段代码不会抛出语法错误?
console.log('hello' ['world'])
两个参数之间应该有逗号,但没有。这不应该引发语法错误吗?
解决方案
您正在下标一个字符串(该[...]
部分被解释为括号符号而不是数组)。结果将是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 :)
推荐阅读
- c# - C# 我可以同时将 FileStream 用于 StreamReader(fs) 和 StreamWriter(fs, append: true) 吗?
- php - URL url 的尾随斜杠仅适用于某些 php url
- swift - 多个switch case fallthroughs和同名关联值的快速编译不稳定并且经常崩溃
- php - Lumen GET 请求参数总是返回空数组
- rx-java - 如果某些 observable 抛出异常,如何继续流式传输?
- r - 最接近 R 中特定列的值
- java - 如何访问 volatile KeyListener ArrayList?
- react-native - react-native 中的静态图像加载问题
- json - Dart / Flutter - 无法从 JSON 响应中分配 bool 值
- android - 后台线程或非 UI 组件中的 LiveData