[英]What's an easy way of storing an array of numbers in Javascript that I can add/remove from?
在C#中,我将创建一个列表,然后可以非常轻松地添加和删除数字。 Javascript中是否存在相同的功能,还是必须编写自己的方法才能使用循环搜索和删除项目?
var NumberList = [];
NumberList.Add(17);
NumberList.Add(25);
NumberList.Remove(17);
等等
我知道我可以使用.push来添加数字,所以我想这确实是在不使用我要查找的循环的情况下删除单个数字的方法。
编辑:当然,如果没有其他方法,那么我将使用循环!:)
Array对象具有这种方法:
var myArray = new Array();
myArray.push(12);
myArray.push(10);
myArray.pop();
所有细节都可以在这里找到
要删除特定值,可以使用一些技巧:
var id = myArray.indexOf(10); // Find the index
if(id!=-1) myArray.splice(id, 1);
如果知道要删除的值只有一个副本,并且必须有多个副本,则必须使用splice和indexOf,则必须在循环中使用splice。
如果您使用的是Underscore.js,则可以使用:
array = _.without(array, 17);
要按值删除数组元素:
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"];
var NumberList = {};
NumberList[17] = true;
NumberList[25] = true;
delete NumberList[17];
这使用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
创建一个包含26个元素的数组,且所有前面的数组元素都设置为undefined
。
相反,使用对象比较稀疏,不会创建其他成员。
您可以存储每个添加的元素(数字)的索引。 然后使用拼接按索引删除。 John具有良好的数组删除功能,可以按索引删除 。
就像是:
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);
如果要就地删除,则可以将indexOf
和splice
一起使用。 要删除所有出现的17,请使用
var index;
while((index = NumberList.indexOf(17)) != -1) {
NumberList.splice(index, 1);
}
如果您不关心就地移除,则可以使用filter
方法。
NumberList = NumberList.filter(function(number) {
return number != 17;
});
我已经通过使用JQuery函数inArray();
解决了这个问题inArray();
结合splice()
。
indexOf
和inArray
似乎是相同的,但是事实证明IE6或7不支持indexOf
,因此我必须自己编写或使用JQuery,无论如何我都使用JQuery。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.