gpt4 book ai didi

javascript - 清空数组的方法?

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:08:16 25 4
gpt4 key购买 nike

我读了题目How do I empty an array in JavaScript?

回答:

Very simple:

A = [];

我对 Daniel Baulig 的评论很感兴趣:

this will NOT empty the array, but create a new, empty array. This might cause problems, especially if there are other references to the array. OP: Please consider to accept Matthew's answer instead. It is the cleaner and formally correct approach. – Daniel Baulig Jan 19 '11 at 13:08

你能告诉我这会导致什么问题吗?

最佳答案

问题是您可能对该数组有另一个引用。

考虑一下:

var A = ['A'];
var B = A;

如果你这样做

A = [];

这仍然会让 B 成为 ['A']。这就是清空(或更改)数组或替换它(您所做的)之间的区别。

当你这样做的时候

A.length=0;

那么 B 也会是空的。

关于javascript - 清空数组的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19866086/

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