如何从数组中删除一个特定值? 类似 :
array.remove(value);
我必须使用核心核心核心JavaScript。 不允许框架 。
如何从数组中删除一个特定值? 类似 :
array.remove(value);
我必须使用核心核心核心JavaScript。 不允许框架 。
当前回答
你的问题没有说明顺序或不同的价值是否是一项要求。
如果您不关心顺序, 并且容器中的值不会超过一次, 请使用“ Set ” 。 它会更快, 更简洁 。
var aSet = new Set();
aSet.add(1);
aSet.add(2);
aSet.add(3);
aSet.delete(2);
其他回答
最基本的解决办法是:
array.key = null;
从数组中删除一个特定元素/字符串可在单班条中进行:
theArray.splice(theArray.indexOf("stringToRemoveFromArray"), 1);
此处:
阵列:要从
将字符串从矩阵中移除:要删除的字符串,而1是要删除的元素数量。
注 注 注 注 注注:如果“字符串要从阵列中移除”不位于数组中,这将删除数组的最后一个元素。
在移除该元素之前先检查该元素是否存在于您的阵列中, 总是很好的做法 。
if (theArray.indexOf("stringToRemoveFromArray") >= 0){
theArray.splice(theArray.indexOf("stringToRemoveFromArray"), 1);
}
取决于客户电脑上是否有新版或旧版的剪贴条:
var array=['1','2','3','4','5','6']
var newArray = array.filter((value)=>value!='3');
或
var array = ['1','2','3','4','5','6'];
var newArray = array.filter(function(item){ return item !== '3' });
“ 3” 是您想要从数组中删除的值。 然后, 数组将变成 :['1','2','4','5','6']
如果您必须支持旧版的 Internet Explorer 版本, 我建议使用以下多填充( 注意: 这是否这是所有现代阵列方法(JavaScript 1.8.5/ECMAScript 5 Array Extras)的100%后向兼容的替代方法,这些方法适用于互联网探索者6+、Firefox 1.5+、Chrome、Safari和Opera。
您可以用所有存取器示例创建索引 :
<div >
</div>
function getIndex($id){
return (
this.removeIndex($id)
alert("This element was removed")
)
}
function removeIndex(){
const index = $id;
this.accesor.id.splice(index.id) // You can use splice for slice index on
// accessor id and return with message
}
<div>
<fromList>
<ul>
{...this.array.map( accesors => {
<li type="hidden"></li>
<li>{...accesors}</li>
})
}
</ul>
</fromList>
<form id="form" method="post">
<input id="{this.accesors.id}">
<input type="submit" callbackforApplySend...getIndex({this.accesors.id}) name="sendendform" value="removeIndex" >
</form>
</div>
我喜欢这个单行道:
arr.includes(val) && arr.splice(arr.indexOf(val), 1)
null
或undefined
作为原型
// remove by value. return true if value found and removed, false otherwise
Array.prototype.remove = function(val)
{
return this.includes(val) && !!this.splice(this.indexOf(val), 1);
}
(是的,我读了所有其他的答案 却找不到一个结合的答案)includes
和splice
在同一行中。 )