【发布时间】: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
typeof 某些数组将始终返回 object。 string?<script>
var x = [typeof x, typeof y][1];
console.log(typeof x);
</script>
【问题讨论】:
标签: javascript html arrays string function
[typeof x, typeof y] 的计算结果为 ["undefined", "undefined"]。 [typeof x, typeof y][1] 计算为 "undefined"。
【讨论】:
好吧,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
【讨论】:
typeof <expression> 计算为字符串,所以
[typeof x, typeof y]
无论x 和y 是什么,都会解析为类似的数组
[<someString>, <someString>]
访问该数组的[1]th 索引将为您提供这些字符串之一,因此typeof <someString> 会产生'string'。
【讨论】: