代码之家  ›  专栏  ›  技术社区  ›  SimpleJ

传递给没有逗号的函数的参数不会引发语法错误?

  •  1
  • SimpleJ  · 技术社区  · 6 年前

    为什么这段代码没有抛出语法错误?

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

    1 回复  |  直到 6 年前
        1
  •  6
  •   ibrahim mahrir    6 年前

    您正在订阅一个字符串( [...] bracket notation 而不是数组)。结果将是 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 :)