+ 3
computed property names in ES6
var i = 0; var a = { ['foo' + ++i]: i, ['foo' + ++i]: i, ['foo' + ++i]: i }; console.log(a.foo1); // 1 console.log(a.foo2); // 2 console.log(a.foo3); // 3 when we change ++i to i++ the output value is : /*2 3 undefined */ why?
1 Odpowiedź
+ 2
Is that "++i" first adds 1 and then assigns it, while "i++" first assigns and then adds 1, there is no property "a.foo3", so it goes "undefined"
var i = 0;
var a = {
['foo' + ++i]: i, // 'foo1': 1
['foo' + ++i]: i, // 'foo2': 2
['foo' + ++i]: i // 'foo3': 3
};
console.log(a.foo1);
// i = i + 1 then i = 1
console.log(a.foo2);
// i = i + 1 then i = 2
console.log(a.foo3);
// i = i + 1 then i = 3
then
var a = {
['foo' + i++]: i, // 'foo0': 0
['foo' + i++]: i, // 'foo1': 1
['foo' + i++]: i // 'foo2': 2
};
console.log(a.foo0); // 0
// i = 0 then i = i + 1
console.log(a.foo1); // 1
// i = 1 then i = i + 1
console.log(a.foo2); // 2
// i = 2 then i = i + 1