如何从数组中删除一个特定值? 类似 :
array.remove(value);
制约:我必须使用核心 JavaScript 。 框架不允许 。
如何从数组中删除一个特定值? 类似 :
array.remove(value);
制约:我必须使用核心 JavaScript 。 框架不允许 。
当前回答
用于解决多个浏览器的问题。 如果存在的话, 它会使用在建浏览器的方法。 如果没有这些方法, 则使用自己的自定义方法。 如果像旧版的互联网探索者一样, 它会使用自己的自定义方法 。
从数组中删除元素( 从网站) 的简单示例 :
_.without([1, 2, 1, 0, 3, 1, 4], 0, 1); // => [2, 3, 4]
其他回答
删除单个元素
function removeSingle(array, element) {
const index = array.indexOf(element)
if (index >= 0) {
array.splice(index, 1)
}
}
删除多个元素, 位置内
这对于确保算法在O(N)时间运行更为复杂。
function removeAll(array, element) {
let newLength = 0
for (const elem of array) {
if (elem !== number) {
array[newLength++] = elem
}
}
array.length = newLength
}
删除多个元素,创建新对象
array.filter(elem => elem !== number)
您可以用所有存取器示例创建索引 :
<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>
您可以使用ES6. 例如,在此情况下删除值“ 3” :
var array=['1','2','3','4','5','6']
var newArray = array.filter((value)=>value!='3');
console.log(newArray);
产出:
["1", "2", "4", "5", "6"]
如果您在数组中有复杂的对象, 您可以使用过滤器 。 在 $. in Array 或 tray. splice 不容易使用的情况下 。 特别是如果对象在数组中可能是浅的 。
例如,如果您有一个带有 Id 字段的对象,而您想要从数组中删除该对象:
this.array = this.array.filter(function(element, i) {
return element.id !== idToRemove;
});
一种用ES6扩展操作器从数组中去除元素的永恒方式。
比方说你想删除4。
let array = [1,2,3,4,5]
const index = array.indexOf(4)
let new_array = [...array.slice(0,index), ...array.slice(index+1, array.length)]
console.log(new_array)
=> [1, 2, 3, 5]