Leo*_*are 2 javascript types type-coercion
当我这样做时:
const foo = [0, 1, 2]
for (i = 0; i < foo.length; i ++){
console.log(foo[i], typeof foo[i])
}
Run Code Online (Sandbox Code Playgroud)
我明白了:
0 number
1 number
2 number
Run Code Online (Sandbox Code Playgroud)
但是当我这样做时:
0 number
1 number
2 number
Run Code Online (Sandbox Code Playgroud)
我明白了:
0 string
1 string
2 string
Run Code Online (Sandbox Code Playgroud)
这里发生了什么??我需要知道哪些规则才能预测这一点?
编辑:我正在运行 Node 12.18.3
Sco*_*cus 10
这里没有强制执行。您实际上是在用两个不同的循环迭代两种不同的原始类型。
for
带计数器的传统循环,用数字计数。
for/in
循环用于迭代对象的属性。对象具有键/属性,它们始终是字符串。所以,当你看到0
,1
和2
,你所看到的琴弦"0"
,"1"
和"2"
。
因此,当您for/in
在array
实例上使用循环时,它由Array
对象的键枚举,其中包括数组索引的字符串表示以及Array
实例的任何可枚举属性。然后,除了数组中的项目之外,您还可以枚举数组的其他属性,如下所示:
const foo = [0, 1, 2];
// Add a property to the array instance
foo.bar = "baz";
for (let item in foo){
// This will log ALL the enumerable properties
// of the object, in this case, including properties
// that are not the array values.
console.log(item, foo[item]);
}
Run Code Online (Sandbox Code Playgroud)
这是查看这一点的另一种方式。下面是一个用for/in
. 请注意,当文字被创建时,键不会被引号包围,但是当它们的类型被测试时(它们是键名,而不是键值),它们被报告为字符串,因为它们隐式是:
let obj = {
key1: "something",
key2: "something else",
foo: 42,
false: true,
99: 100
};
for(let prop in obj){
// Note that even the unquoted key name of
// false is implicitly a string, not a Boolean
// and the 99 key is a string, not a number
console.log(prop, "(" + typeof prop + ")", obj[prop], "(" + typeof obj[prop] + ")");
}
Run Code Online (Sandbox Code Playgroud)
如文档中所述(上面的链接):
for...in 语句迭代对象的所有以字符串为键的可枚举属性(忽略由 Symbols键的对象),包括继承的可枚举属性。
归档时间: |
|
查看次数: |
52 次 |
最近记录: |