Eloquent JavaScript - 数组有属性吗?

120 阅读2分钟

数组有属性和属性名称吗?

看第四章Data Structures: Objects and Arrays的时候,有一些思考,思考不一定准确,但也觉得挺有意思的。 根据我的理解,数组属于对象(一个数组就是一个对象),它有属性(properties),有属性名称(property names)和属性值(property values)。先看一个数组的例子:

let listOfNumbers = [2, 3, 5, 7, 11]; 
console.log(listOfNumbers[2]); 
// -> 5
console.log(listOfNumbers[0]); 
// -> 2
console.log(listOfNumbers[2 - 1]); 
// -> 3

作者说:

The elements in an array are stored as the array's properties, using numbers as property names.

那我们先来看怎么获取这个数组的属性名称。因为数组是对象,所以可以用Object.keys()这个函数来进行获取。

let listOfNumbers = [2, 3, 5, 7, 11]; 
console.log(Object.keys(listOfNumbers)); 

console.log(Object.keys(listOfNumbers))输出的结果是:["0", "1", "2", "3", "4"],所以验证了"0", "1", "2", "3", "4"就是listOfNumbers这个数组的属性名称。

属性获取:Dot Notation vs Bracket Notation

object.x vs object[x]的区别:

  • When using a dot, the word after the dot is the literal name of the property.
  • When using square brackets, the expression between the brackets is evaluated to get the property name.
  • Property names are strings. They can be any strings, but the dot notation works only with names that look like valid binding names. So if you want to access a property named 2 or John Doe, you must use square brackets: object[2] or object["John Doe"].

对于object[x]方括号[ ]里面必须是string,比如object["firstName"]object["age"]。如果不是string,是一个expression,那么对expression进行求值之后,也会有一个转换为string的操作。
也就是说object[x]是先对x这个expression进行求值(evaluate),然后把求得的值转为string。用数组来举例:

let listOfNumbers = [2, 3, 5, 7, 11]; 
const two = 2; 
console.log(listOfNumbers[two]);   // -> 5

首先,我们上面已经知道,listOfNumbers这个数组的属性名称是["0", "1", "2", "3", "4"]
我的理解是,listOfNumbers[two]这里,是先对two求值,求得是数字2,然后再把数字2转为string的2,string的2对应元素5的属性名称。
上面的例子和解释看上去有点过于复杂?虽然我是这样理解的,但我仍然有疑问,既然数组就是对象,对象的bracket notation到底有没有把上面这种情况的数字2转为string的2?

经过验证,数字2应该是有被转换成"2"

let listOfNumbers = [2, 3, 5, 7, 11]; 
const two = “2”;      // here two is a string, not an integer
console.log(listOfNumbers[two]);   // -> 5