在 JavaScript 中覆盖数组
如何覆盖(或取消设置然后设置)数组?似乎 "array = new_array"
不起作用。
How do I overwrite (or unset and then set) an array? Seems like "array = new_array"
doesn't work.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
要创建一个空数组来分配给变量,您可以使用 Array 构造函数:
或者您可以使用空数组文字:
如果您对一个数组有多个引用,则必须清空实际的数组对象而不是替换引用对此,你可以这样做:
To create an empty array to assign to the variable, you can use the Array constructor:
Or you can use an empty array literal:
If you have several references to one array so that you have to empty the actual array object rather than replacing the reference to it, you can do like this:
清除数组
http://2ality.com/2012/ 12/clear-array.html
Clearing an array
http://2ality.com/2012/12/clear-array.html
这应该有效。
如果没有,请提供更多详细信息。
This should work.
If not, please provide more details.
我不太确定您要做什么,但有几种方法可以重置数组。
您可以迭代现有数组并将每个索引设置为 null(或空字符串或 0 或您认为重置的任何值):
您也可以只更新对对象的新实例的现有引用:
I'm not exactly sure what you're trying to do, but there are a couple of ways to go about resetting an array.
You could just iterate through the existing array and set each index equal to null (or an empty string or 0 or whatever value you consider to be a reset):
You could also just update the existing reference to a new instance of an object:
使用 Slice()
像这样 ->
array = new_array.slice(0);
Using Slice()
like this ->
array = new_array.slice(0);
嗯,看来问题不是我想的那样;我的错误是以下几行,毕竟与数组没有任何关系:
sms.original 成为一个对象,然后 sms.messages 变成 < em>sms.original (我只是希望它们具有相同的值)。这些对象包含一个名为 items 的数组,该数组在 sms.original 对象中保持静态,但是当我更改 sms.messages 时,原始对象对象也变了。解决方案很简单:
抱歉打扰您,我应该详细说明,但代码被分成多个文件和函数。不管怎样,谢谢你们,现在 Guffa 的拼接技术对我有用了。
Hm, it seems like the problem wasn't what I thought; my mistake was the following rows, which after all havn't got anything to do with arrays at all:
sms.original becomes an object, and then sms.messages becomes sms.original (I just wanted them to have the same value). The objects contain an array named items which was ment to remain static in the sms.original object, but when I changed sms.messages the original object changed as well. The solution was simple:
Sorry for bothering you, I should have elaborated but the code is splited in multiple files and functions. Thank you guys anyway, now does Guffa's splice technique work for me.