如何从数组中删除一个特定值? 类似 :
array.remove(value);
我必须使用核心核心核心JavaScript。 不允许框架 。
如何从数组中删除一个特定值? 类似 :
array.remove(value);
我必须使用核心核心核心JavaScript。 不允许框架 。
当前回答
您可以用所有存取器示例创建索引 :
<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>
其他回答
使用 jQuery 的阵列 :
A = [1, 2, 3, 4, 5, 6];
A.splice($.inArray(3, A), 1);
//It will return A=[1, 2, 4, 5, 6]`
注意: 如果元素未找到, 在阵列中返回 - 1 。
您可以使用Set
,然后使用delete
函数 :
const s = Set;
s.add('hello');
s.add('goodbye');
s.delete('hello');
根据索引删除
函数返回在索引中没有元素的数组副本 :
/**
* removeByIndex
* @param {Array} array
* @param {Number} index
*/
function removeByIndex(array, index){
return array.filter(function(elem, _index){
return index != _index;
});
}
l = [1,3,4,5,6,7];
console.log(removeByIndex(l, 1));
$> [ 1, 4, 5, 6, 7 ]
以值删除
函数返回没有值的数组副本。
/**
* removeByValue
* @param {Array} array
* @param {Number} value
*/
function removeByValue(array, value){
return array.filter(function(elem, _index){
return value != elem;
});
}
l = [1,3,4,5,6,7];
console.log(removeByValue(l, 5));
$> [ 1, 3, 4, 6, 7]
您只需要按元素或索引过滤 :
var num = [5, 6, 5, 4, 5, 1, 5];
var result1 = num.filter((el, index) => el != 5) // for remove all 5
var result2 = num.filter((el, index) => index != 5) // for remove item with index == 5
console.log(result1);
console.log(result2);
使用.indexof () 和.spolice () - 可变模式
这里有两种情况:
const drinks = [ 'Tea', 'Coffee', 'Milk'];
const id = 1;
const removedDrink = drinks.splice(id, 1);
console.log(removedDrink)
const drinks = ['Tea','Coffee', 'Milk'];
const id = drinks.indexOf('Coffee'); // 1
const removedDrink = drinks.splice(id, 1);
// ["Coffee"]
console.log(removedDrink);
// ["Tea", "Milk"]
console.log(drinks);
使用. filter () - 不可变模式
你可以想到的最好方式是 — — 而不是“删除”该项目,而是“创造”一个新的阵列,只是不包含该项目。 所以我们必须找到它,完全省略它。
const drinks = ['Tea','Coffee', 'Milk'];
const id = 'Coffee';
const idx = drinks.indexOf(id);
const removedDrink = drinks[idx];
const filteredDrinks = drinks.filter((drink, index) => drink == removedDrink);
console.log("Filtered Drinks Array:"+ filteredDrinks);
console.log("Original Drinks Array:"+ drinks);