2011-03-11 40 views
2

在C#中我会创建一个List,然后我可以很容易地添加和删除数字。 Javascript中是否存在相同的功能,还是我必须编写自己的方法来使用循环搜索和删除项目?什么是一种简单的方法来存储我可以添加/删除的JavaScript数字数组?

var NumberList = []; 

NumberList.Add(17); 
NumberList.Add(25); 
NumberList.Remove(17); 

我知道我可以使用.push增加号码,所以我想这是真的如何删除个别号码不使用,我正在寻找一个循环。

编辑:当然,如果没有其他办法,然后我将使用一个循环:)

回答

0

我已经使用jQuery功能inArray();splice()相结合解决了这个问题。

indexOfinArray似乎是相同的,但indexOf在IE6或7中不支持,因此我必须自己编写或使用JQuery,而且我仍然使用JQuery。

2

的阵列客体具有这种方法:

var myArray = new Array(); 
myArray.push(12); 
myArray.push(10); 
myArray.pop(); 

所有的细节都可以找到here

要删除特定值时,一些技巧是可能的:

var id = myArray.indexOf(10); // Find the index 
if(id!=-1) myArray.splice(id, 1); 
2

如果您知道只有一个要删除的值的副本,并且如果可以有多个副本,则必须使用splice和indexOf,然后您必须在循环中使用拼接。

如果你使用Underscore.js那么你可以使用:

array = _.without(array, 17); 
0
var NumberList = {}; 

NumberList[17] = true; 
NumberList[25] = true; 

delete NumberList[17]; 

这里使用了“关联数组” -characteristic JavaScript对象,让你存储和对象检索由索引值。

我用true作为值,但你可以使用任何你喜欢的,因为它并不重要(至少按你的例子​​)。你当然可以在那里存储更多有用的东西。使用true有很好的副作用,你可以做一个存在检查这样的:

if (NumberList[25]) // evaluates to "true" 

if (NumberList[26]) // evaluates to "undefined" (equivalent to "false" here) 

同样会与实际的数组对象的工作,顺便说一句。

var NumberList = []; 

NumberList[17] = true; 
NumberList[25] = true; 

delete NumberList[17]; 

但这些将不“疏” - NumberList[25] = true创建具有设置为undefined前面的所有数组元素的26个元素的阵列。

改用对象是稀疏的,不会创建额外的成员。

+0

这也是我的想法,但如果提问者真的需要一个数组 - 这是行不通的。 – 2011-03-11 16:05:14

+0

有趣的是,在IE6 +浏览器中是否支持删除?另外,如果数字范围是10万,那么会不会有相关的开销? – NibblyPig 2011-03-11 16:06:15

+0

@SLC正如我所解释的,如果您使用对象(通过'{}'),则不会有开销。如果你使用数组(通过'[]'),会有相当大的开销。是的,IE6支持'delete'。它通常只是其中一个鲜为人知的/使用过的JS特性。 – Tomalak 2011-03-11 16:09:32

1

要通过值删除数组元素:

Array.prototype.removeByValue = function(val) { 
    for(var i=0; i<this.length; i++) { 
     if(this[i] == val) { 
      this.splice(i, 1); 
      break; 
     } 
    } 
} 

var myarray = ["one", "two", "three", "four", "five"]; 
myarray.removeByValue("three"); 
console.log(myarray); // ["one", "two", "four", "five"]; 

或在您的案件数的数组:

var myarray = [1, 2, 3, 4, 5]; 
myarray.removeByValue(3); 
console.log(myarray); // [1, 2, 4, 5]; 

通过索引删除你将不得不使用splice()

myarray.splice(2,1); //position at 2nd element and remove 1 element 
console.log(myarray); // ["one", "two", "four", "five"]; 
0

你可以存储每个添加元素(数)的索引。然后使用拼接按索引删除。 John has a good array remove function to remove by index

喜欢的东西:

var array = []; 
var number = { val: 10, index: null }; 

// add to array 
array.push(number.val); 
number.index = array.length - 1; 

// remove (using John's remove function) 
array.remove(number.index); 
// remove using splice 
array.splice(number.index, 1); 
0

如果你要就地拆除,然后indexOfsplice可以一起使用。要删除的17所有出现,使用

var index; 
while((index = NumberList.indexOf(17)) != -1) { 
    NumberList.splice(index, 1); 
} 

如果你不关心就地清除,然后可以使用filter方法。

NumberList = NumberList.filter(function(number) { 
    return number != 17; 
}); 
相关问题