有人可以解释这两种情况之间的区别吗?也就是说,为什么 b 在第一个中没有被重新定义,但在第二个中被重新定义了?
a = [0,1,2,3,4]
b = a //b = [0,1,2,3,4]
a = 4
console.log(b) //b is still [0,1,2,3,4]
//redefining a AFTER saying b = a will NOT change b
/
a = [0,1,2,3,4]
b = a //b = [0,1,2,3,4]
for ( i = 0; i < a.length; i++){
a[a.length - (i + 1)] = b[i]
} //I though this loop would redefine a as b in reverse. But this happens:
console.log(a) //both a and b have changed to [0,1,2,1,0]
console.log(b) //I don't understand why b changed at all, since a is being redefined
//AFTER I saved b as [0,1,2,3,4] and the = sign is supposed to just
//assign the value on the right to the value on the left
最佳答案
在第一种情况下,您已将单个数组的引用存储到两个变量中 - a
和 b
。然后您更改了 a
,它删除了引用,现在包含 4
。在此之后,您只有引用数组的变量 b
并且您只能通过 b
更改该数组的项目。
在第二种情况下,您再次在变量 a
和 b
中有一个数组的两个引用。但是当你做一些工作并更改一个项目时 a[a.length - (i + 1)] = b[i]
,这个语句只是通过引用并更改单个数组中的项目对象,因为 b
也引用同一个数组,通过变量 b
可以看到相同的变化。
所以这条语句 a[a.length - (i + 1)] = b[i]
获取位于 b[i]
的项目并将其分配给a[a.length - (i + 1)]
,但这也等同于语句 b[b.length - (i + 1)]
。
简而言之,您在 a
和 b
中有相同的引用,如果您通过 a
更改数组,它也会更改为 b
,因为它们指的是同一个数组。
如果要更改第一个数组而不影响第二个数组,则需要创建两个单独的数组。您可以通过 slice
函数或数组展开运算符 ([...a]
) 来完成,或者只需调用 a.reverse
返回反转数组.
const a = [0,1,2,3,4];
const b = a.slice(); // splice returns a new array
for(let i = b.length - 1; i >= 0; i--) {
a[a.length - i - 1] = b[i];
}
console.log(a);
console.log(b);
或者直接调用reverse
函数
let a = [0,1,2,3,4];
let b = [...a];
a.reverse();
console.log(a);
console.log(b);
关于javascript - 如果 b = a,为什么在下一行重新定义 a 后 b 会发生变化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47826795/