Today encountered a pit, specifically not much to say, directly on the code
var a = [[],[],[1,2,3]]var b = [' Color ', ' size ', ' size ']var arr = []fo R(Let i = 0; i < a.length; i + +) {= { }for (Let j = 0; J < A[i].length; j + +) {= a[i][j] arr.push (obj) console.log (arr) console.log (obj) }} Console.log (arr)
I expect the result of ARR should be
[{' Size ': 1}, {' Size ': 2}, {' Size ': 3}]
Finally arr's the result is this
[{' Size ': 3}, {' Size ': 3}, {' Size ': 3}]
Ask in a group of friends and finally come to your own conclusion-this is because of the different value types and reference types.
The values in JavaScript are roughly divided into two types, one value type and one reference type.
Value types: Numeric, Boolean, null, undefined
Reference types: objects, arrays, functions
The obj in our example is different each time it is printed, but because it is a reference type, arr is also a reference type, even if obj is push into arr, it just push into a memory address, so the last obj becomes 3, and the obj referenced in arr will all become 3. It's amazing, and the final solution is simple.
var a = [[],[],[1,2,3]]var b = [' Color ', ' size ', ' size ']var arr = []fo R(Let i = 0; i < a.length; i + +) {for (let j = 0; J < A[i].length; J + +) { = {} = A[i][j] arr.push (obj) }}console.log (arr)
As long as the declaration of obj is placed inside the innermost loop, each loop will be a separate memory address, so that the last obj, even if it becomes 3, will not be affected by the previous obj because their memory address has different roots.
Initial study of JavaScript value types and reference types