当我在temp上使用splice时,mainArray也被修改了,这是正常的吗?
console.log(mainArray);
var temp = mainArray;
temp.airfares.splice(index, 1);
最佳答案
这是因为 temp
不是一个全新的数组,只是对 mainArray
的引用。您需要复印一份。
使用 Array.prototype.slice()
轻松复制数组常见。请注意,它不会复制每个元素,但会复制数组本身(因此您可以稍后推送或删除元素)。
例如:
var data = [1, 2, 3, 4, 5];
document.getElementById("original").textContent = JSON.stringify(data);
var ref = data;
var copy = data.slice();
// Add some values to data, ref will change but copy won't
data.push(6, 7, 8);
document.getElementById("ref").textContent = JSON.stringify(ref);
document.getElementById("copy").textContent = JSON.stringify(copy);
<pre id="original"></pre>
<pre id="ref"></pre>
<pre id="copy"></pre>
关于javascript - 拼接临时数组会修改主数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28200260/