javascript - 在js取值的时候, 这种现象叫什么, 如何解释呢?
本文介绍了javascript - 在js取值的时候, 这种现象叫什么, 如何解释呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
问 题
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>test js</title>
</head>
<body>
<h1>JS Test</h1>
<script>
var arr = [
'Dell',
'HP',
'Apple',
'Acer'
];
var map = {
0: 'DELL',
1: 'HP',
2: 'APPLE',
3: 'ACER'
};
console.log(arr[1]);// HP
console.log(map[1]);// HP
console.log(arr[01]);// HP
console.log(map[01]);// HP
console.log(arr['1']);// HP
console.log(map['1']);// HP
console.log(arr['01']);// undefined
console.log(map['01']);// undefined
</script>
</body>
</html>
解决方案
所有索引都是字符串,所有数组都是对象,数组不过只是比较特殊的对象而已
所有用 a[i]
访问的 a
的时候 会计算 i
的值并转换为字符串
计算 a[01]
的时候 先计算了 01
的值,在非严格模式下 01
是数 1
的八进制表示
即 01 == 1
所以 a[01] == a[1]
计算完 i 的值之后把它转为字符串a[1] === a["1"]
因为 "1" != "01"
所以 a["1"] != a["01"]
关于数组和对象的索引之间的关系:
数组的 index
是 从 0 到 2^64-2 之间的整数 key
(最后也转为字符串)
数组的 length
值至少比数组中最大的 index
值大 1
这篇关于javascript - 在js取值的时候, 这种现象叫什么, 如何解释呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文