如何从数组中删除一个特定值? 类似 :

array.remove(value);

制约:我必须使用核心 JavaScript 。 框架不允许 。


当前回答

如果您想要删除删除位置的新数组, 您总是可以删除特定元素并过滤数组。 它可能需要为不执行过滤方法的浏览器扩展数组对象, 但从长远来看, 它比较容易, 因为您所做的只是:

var my_array = [1, 2, 3, 4, 5, 6];
delete my_array[4];
console.log(my_array.filter(function(a){return typeof a !== 'undefined';}));

它应显示[1、2、3、4、6]。

其他回答

通过传递其值来删除项目 --

const remove=(value)=>{
    myArray = myArray.filter(element=>element !=value);

}

将项目通过索引编号删除 -

  const removeFrom=(index)=>{
    myArray = myArray.filter((_, i)=>{
        return i!==index
    })
}

如果你想删除几个项目, 我发现这是最容易的:

const oldArray = [1, 2, 3, 4, 5]
const removeItems = [1, 3, 5]

const newArray = oldArray.filter((value) => {
    return !removeItems.includes(value)
})

console.log(newArray)

产出:

[2, 4]

如果您想要 [.].remove(el) 类似语法的语法, 和其他编程语言一样, 那么您可以添加此代码 :

// Add remove method to Array prototype
Array.prototype.remove = function(value, count=this.length) {
    while(count > 0 && this.includes(value)) {
        this.splice(this.indexOf(value), 1);
        count--;
    }
    return this;
}

用法

// Original array
const arr = [1,2,2,3,2,5,6,7];

// Remove all 2s from array
arr.remove(2); // [1,3,5,6,7]

// Remove one 2 from beginning of array
arr.remove(2, 1); // [1,2,3,2,5,6,7]

// Remove two 2s from beginning of array
arr.remove(2, 2); // [1,3,2,5,6,7]

您可以根据您的需求操控该方法 。

您可以用所有存取器示例创建索引 :

<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>

删除在索引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);
}