gpt4 book ai didi

Javascript 数组反向函数意外行为

转载 作者:搜寻专家 更新时间:2023-11-01 04:44:10 24 4
gpt4 key购买 nike

我想了解为什么情况 1 和情况 2 不会返回相同的结果。

情况一:

var array1 = ["1", "2", "3"];
var array2 = array1.reverse();

console.log(array1); // ["3", "2", "1"]
console.log(array2); // ["3", "2", "1"] Why this doesn't work ?

情况二:

var array1 = ["1", "2", "3"];
var array2 = array1;

console.log(array1); // ["1", "2", "3"]
console.log(array2.reverse()); // ["3", "2", "1"] Why this works ?

最佳答案

情况 1

The reverse method transposes the elements of the calling array object in place, mutating the array, and returning a reference to the array.

情况 2 中,您有相同 引用。您正在打印 array1 数组 before 反转它。

var array1 = ["1", "2", "3"];
var array2 = array1;

console.log(array1); // [ '1', '2', '3' ]
console.log(array2.reverse()); // [ '3', '2', '1' ]
console.log(array1); // [ '3', '2', '1' ]

关于Javascript 数组反向函数意外行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36828835/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com