seb*_*seb 1 javascript arrays jquery
当我在temp上使用splice时,mainArray也被修改了,这是正常的吗?
console.log(mainArray);
var temp = mainArray;
temp.airfares.splice(index, 1);
Run Code Online (Sandbox Code Playgroud)
这是因为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);Run Code Online (Sandbox Code Playgroud)
<pre id="original"></pre>
<pre id="ref"></pre>
<pre id="copy"></pre>Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2685 次 |
| 最近记录: |