4.2 Object and Array Initializers Object and array initializers are expressions whose value is a newly created object or array. These initializer expressions are sometimes called “ object literals ” and “ array literals.” Unlike true literals, however, they are not primary expressions, because they include a number of subexpressions that specify property and element values. Array initializers have a slightly simpler syntax, and we ’ ll begin with those. An array initializer is a comma-separated list of expressions contained within square brackets. The value of an array initializer is a newly created array. The elements of this new array are initialized to the values of the comma-separated expressions: [] // An empty array: no expressions inside brackets means no elements [1+2,3+4] // A 2-element array. First element is 3, second is 7 The element expressions in an array initializer can themselves be array initializers, which means that these expressions can create nested arrays: var matrix = [[1,2,3], [4,5,6], [7,8,9]];
The element expressions in an array initializer are evaluated each time the array ini- tializer is evaluated. This means that the value of an array initializer expression may be different each time it is evaluated.
淘宝翻译版: JavaScript 对数组初始化表达式进行求值得时候,数组初始化表达式中的元素表达式也都会各自计算一次。也就是说,数组初始化表达式每次计算的值都有可能是不同的.
问题: 1 ,为什么不同? 2 ,意味着什么?怎么样表现?有什么坑能举个栗子么?
Undefined elements can be included in an array literal by simply omitting a value be- tween commas. For example, the following array contains five elements, including three undefined elements: var sparseArray = [1,,,,5];
1
sturloly OP 自我理解尝试,求大神确认下, Chrome 调试:
var x =1 声明 1 打印 var b = [[1+x],[2+x],[3+x]]; 声明 b[0] 打印 [2] x =2 声明 2 打印 b[0] 声明 [2] 打印 b 尝试调用一下 b[0] [2] 没解析 var b = [[1+x],[2+x],[3+x]]; //重新声明下 b[0] [3] 重新解析元素表达式了 求问书上的那句话是想表达这个点么? |
2
xxxyyy 2016-09-06 12:15:05 +08:00 1
var obj = {
_foo: 0, get foo() { return this._foo++; }, }; var ary = [obj.foo, obj.foo, obj.foo]; console.log(ary); |
3
YuJianrong 2016-09-06 14:49:56 +08:00 1
@sturloly 是的就是你 demo 的意思, array 每次运行到的时候才会求值然后构造 array ,所以运行时的结果不同同样的 array 表达式的值也不同。就是说这个意思。
|
4
fancy967 2016-09-06 16:04:40 +08:00 1
呃,这个不是很常见的情况吗,数组的初始化值是动态的,所以每次初始化的结果不一定相等
|
5
sturloly OP 谢谢各位,本来不理解的是如果只是 var x =[1,2,3] 那再次重复声明下 var x= [1,2,3,4]当然不一样是句废话。 那再次声明 var x=[1,2,3]的话那是全等的啊怎么会可能不一样。所以其实是这句话可能缺少了“在数组内部嵌套的元素数组中,有对象类型的量”这个条件来使之可能被动态修改。所以本菜踩坑少就纠结了
|