javascript javascript拼接数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8159008/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
javascript splicing array
提问by frenchie
I have an array of object and I'm looking to remove an element. However, the splice method seems to return the element removed, not the array without the element I wanted to remove.
我有一个对象数组,我想删除一个元素。但是, splice 方法似乎返回删除的元素,而不是没有我想要删除的元素的数组。
This is what I have
这就是我所拥有的
var TheArray = TheObject.Array;
TheArray = TheArray.splice(TheIndex, 1); //TheIndex is the index of the element I want to remove
TheObject.Array = TheArrray;
When I debug and run this code, TheObject.Array contains the element I wanted to remove.
当我调试并运行此代码时,TheObject.Array 包含我想要删除的元素。
What am I doing wrong? Thanks for your suggestions.
我究竟做错了什么?感谢您的建议。
回答by Jon Newmuis
splice
returns the removed element, but modifies the element on which it was called. So in your example, TheArray
is updated in place, and should no longer contain the removed element.
splice
返回删除的元素,但修改调用它的元素。因此,在您的示例中,TheArray
已就地更新,并且不应再包含已删除的元素。
A more concrete, simplified example of how to use splice
is as follows:
一个更具体、更简单的使用示例splice
如下:
var myArr = ["a", "b", "c", "d"];
var elem = myArr.splice(2, 1);
// elem => ["c"]
// myArr => ["a", "b", "d"]
回答by Kevin Anthony Oppegaard Rose
You are setting the value of TheArray
to that of the item you are removing.
您正在将 的值设置为TheArray
要删除的项目的值。
Rewrite your code like this:
像这样重写你的代码:
var TheArray = TheObject.Array;
TheArray.splice(TheIndex, 1); //TheIndex is the index of the element I want to remove
TheObject.Array = TheArrray;
回答by Robert Van Sant
do an alert on your array to make sure the array is correct, also you may need to do a parseInt() around your variable (ie TheArray = TheArray.splice(parseInt(TheIndex), 1);) to make sure it's set to be an integer and not a string :)
在你的数组上做一个警报以确保数组是正确的,你可能还需要在你的变量周围做一个 parseInt()(即 TheArray = TheArray.splice(parseInt(TheIndex), 1);)以确保它被设置为是一个整数而不是一个字符串:)
i hope this helps
我希望这有帮助