【问题标题】:typeof 2D array is coming out to be String. Why?typeof 2D 数组将变为 String。为什么?
【发布时间】:2019-07-20 19:25:00
【问题描述】:
  • 我有一些看起来像二维数组的东西。
  • typeof 某些数组将始终返回 object。
  • 那么,为什么在下面的例子中,返回类型是string?

<script>

  var x = [typeof x, typeof y][1];
  console.log(typeof x);

</script>

【问题讨论】:

    标签: javascript html arrays string function


    【解决方案1】:

    [typeof x, typeof y] 的计算结果为 ["undefined", "undefined"]。 [typeof x, typeof y][1] 计算为 "undefined"。

    【讨论】:

      【解决方案2】:

      好吧,typeof 返回一个字符串,所以任何typeof typeof 也将是一个字符串:

      var x = [typeof x, typeof y][1]; //x is undefined when this is run
      console.log(typeof x); //typeof "undefined" == string
      

      在上面的代码中,[typeof x, typeof y] 等于["undefined", "undefined"]。

      这是一个简单的演示:

      var x = [typeof x, typeof y];
      console.log(x); //returns ["undefined", "undefined"]
      var myVar = x[1];
      console.log(myVar); //returns "undefined"
      console.log(typeof myVar); //returns string, because "undefined" is a string

      【讨论】:

        【解决方案3】:

        typeof &lt;expression&gt; 计算为字符串,所以

        [typeof x, typeof y]
        

        无论x 和y 是什么,都会解析为类似的数组

        [<someString>, <someString>]
        

        访问该数组的[1]th 索引将为您提供这些字符串之一,因此typeof &lt;someString&gt; 会产生'string'。

        【讨论】:

          猜你喜欢
          • 2018-11-24
          • 1970-01-01
          • 2013-01-08
          • 1970-01-01
          • 2016-10-28
          • 2013-08-14
          • 1970-01-01
          • 2023-04-08
          • 2021-07-16
          相关资源
          最近更新 更多