如何从数组中删除一个特定值? 类似 :
array.remove(value);
制约:我必须使用核心 JavaScript 。 框架不允许 。
如何从数组中删除一个特定值? 类似 :
array.remove(value);
制约:我必须使用核心 JavaScript 。 框架不允许 。
当前回答
删除上次的元素
arrName.pop();
删除第一个元素
arrName.shift();
从中间删除
arrName.splice(starting index, number of element you wnt to delete);
Example: arrName.splice(1, 1);
删除最后一个元素
arrName.splice(-1);
使用数组索引编号删除
delete arrName[1];
其他回答
删除在索引i 上的元素, 不突变原始数组 :
/**
* removeElement
* @param {Array} array
* @param {Number} index
*/
function removeElement(array, index) {
return Array.from(array).splice(index, 1);
}
// Another way is
function removeElement(array, index) {
return array.slice(0).splice(index, 1);
}
正在删除带有索引和相交点的值 !
function removeArrValue(arr,value) {
var index = arr.indexOf(value);
if (index > -1) {
arr.splice(index, 1);
}
return arr;
}
您可以对每个数组项进行循环, 如果在您的数组中存在的话, 可以复制并连接它 。
function destroy(arr, val) {
for (var i = 0; i < arr.length; i++) if (arr[i] === val) arr.splice(i, 1);
return arr;
}
我不知道你如何期待阵列.remove( int) 的行为。 我可以想到三种可能性, 你可能会想要。
要删除索引 i 中的数组元素:
array.splice(i, 1);
如果您想要从数组中删除带有数值数的每个元素 :
for (var i = array.length - 1; i >= 0; i--) {
if (array[i] === number) {
array.splice(i, 1);
}
}
如果您只想在索引 I 中使元素不再存在, 但是您不想让其它元素的索引改变 :
delete array[i];
您可以用所有存取器示例创建索引 :
<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>