删除阵列键时它包含在JavaScript字符串 [英] Delete an array key when it contains a string in javascript
问题描述
我在JavaScript的一个数组,看起来像这样:
ARR = [md51234,md55234]
我试图做去除这一个项目:
删除ARR [md51234]
不过,这似乎并没有工作。有另一种方式来删除此?
@dystroy提供了答案,我的indexOf添加到阵列原型不兼容的浏览器:
如果(!Array.prototype.indexOf){
Array.prototype.indexOf =功能(OBJ,开始){
对于(VAR I =(启动|| 0),J = this.length; I<焦耳;我++){
如果(这[一] === OBJ){回报我; }
}
返回-1;
}
}
您必须提供的索引,而不是值:
删除ARR [0];
另外,您也可以使用的indexOf 大多数浏览器
删除ARR [arr.indexOf(md51234)];
但是请注意,删除不作阵短,只是做一个值undefined。有使用后,您的阵列删除
是
[未定义md55234]
如果你想在阵列短,用
arr.splice(0,1); //第一个参数是元素删除的索引,第二个是元素删除的数
这使得
[md55234]
I have an array in javascript that looks like this:
arr = ["md51234","md55234"]
I'm trying to remove an item from this by doing:
delete arr["md51234"]
But this doesn't seem to work. Is there another way to remove this?
@dystroy provided the answer, I added indexOf to the array prototype for non-compliant browsers:
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function(obj, start) {
for (var i = (start || 0), j = this.length; i < j; i++) {
if (this[i] === obj) { return i; }
}
return -1;
}
}
You must provide the index, not the value :
delete arr[0];
Alternatively, you could also use indexOf on most browsers
delete arr[arr.indexOf("md51234")];
But note that delete doesn't make the array shorter, it just make a value undefined. Your array after having used delete
is
[undefined, "md55234"]
If you want to make the array shorter, use
arr.splice(0, 1); // first parameter is index of element to remove, second one is number of elements to remove
This makes
["md55234"]
这篇关于删除阵列键时它包含在JavaScript字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!