如何从数组中删除一个特定值? 类似 :
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>
其他回答
如果您在数组中有复杂的对象, 您可以使用过滤器 。 在 $. in Array 或 tray. splice 不容易使用的情况下 。 特别是如果对象在数组中可能是浅的 。
例如,如果您有一个带有 Id 字段的对象,而您想要从数组中删除该对象:
this.array = this.array.filter(function(element, i) {
return element.id !== idToRemove;
});
您可以使用标准__proto__
JavaScript 和定义此函数。例如,
let data = [];
data.__proto__.remove = (n) => { data = data.flatMap((v) => { return v !== n ? v : []; }) };
data = [1, 2, 3];
data.remove(2);
console.log(data); // [1,3]
data = ['a','b','c'];
data.remove('b');
console.log(data); // [a,c]
我本人也有这个问题(在更换阵列是可以接受的情况下),
var filteredItems = this.items.filter(function (i) {
return i !== item;
});
要给上面的片段略加上下文:
self.thingWithItems = {
items: [],
removeItem: function (item) {
var filteredItems = this.items.filter(function (i) {
return i !== item;
});
this.items = filteredItems;
}
};
此解决方案应该同时使用引用项和值项。 它都取决于您是否需要保持对原始数组的引用, 以判断该解决方案是否适用 。
最简单的方法可能是使用过滤功能。例如:
let array = ["hello", "world"]
let newarray = array.filter(item => item !== "hello");
console.log(newarray);
// ["world"]
减少方法的利润如下:
(a) 需要按索引删除某一要素:
function remove(arr, index) {
return arr.reduce((prev, x, i) => prev.concat(i !== index ? [x] : []), []);
}
b) 需要删除元素值(int)的元素:
function remove(arr, value) {
return arr.reduce((prev, x, i) => prev.concat(x !== value ? [x] : []), []);
}
这样我们就可以返回一个新的阵列( 将会以酷酷的功能方式- 比使用推或组合要好得多) , 并删除元素 。