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

array.remove(value);

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


当前回答

大部分答案都用...

  1. 索引和交点
  2. 删除删除
  3. 过滤过滤器
  4. 常设经常经常 经常经常for loop

虽然所有解决办法都应采用这些方法,但我认为我们可以使用字符串操作.

需要注意的关于这一解决办法的要点 -- --

  1. 它会在数据中留下漏洞(可以通过额外的过滤器来清除)
  2. 此解决方案不仅用于原始搜索值,而且用于工作对象.

诀窍是...

  1. stringify数据集和搜索值
  2. 用空字符串替换输入数据集中的搜索值
  3. 返回返回split分隔符上的数据,.
    remove = (input, value) => {
        const stringVal = JSON.stringify(value);
        const result = JSON.stringify(input)

        return result.replace(stringVal, "").split(",");
    }

这里创建了一个测试对象和数字 JSF 的 JSF 。 。 。https://jsfiddle.net/4t7zhkce/33/

检查remove方法在小提琴中。

其他回答

最简单的方法可能是使用过滤功能。例如:

let array = ["hello", "world"]
let newarray = array.filter(item => item !== "hello");
console.log(newarray);
// ["world"]

我还有一个从阵列中移除的好办法:

var words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];

const result = words.filter(word => word.length > 6);

console.log(result);
// expected output: Array ["exuberant", "destruction", "present"]

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter

我对JavaScript很新,需要这个功能。我只是写了这个:

function removeFromArray(array, item, index) {
  while((index = array.indexOf(item)) > -1) {
    array.splice(index, 1);
  }
}

然后,当我想使用它:

//Set-up some dummy data
var dummyObj = {name:"meow"};
var dummyArray = [dummyObj, "item1", "item1", "item2"];

//Remove the dummy data
removeFromArray(dummyArray, dummyObj);
removeFromArray(dummyArray, "item2");

输出 - 如预期的那样。 [“项目1”、“项目1”]

你可能跟我有不同的需要,所以你可以轻易地修改,以适合他们。我希望这能帮助别人。

我喜欢这个组合的版本, 以其值来去除元素, 使用$.inArray:

$(document).ready(function(){
    var arr = ["C#","Ruby","PHP","C","C++"];
    var itemtoRemove = "PHP";
    arr.splice($.inArray(itemtoRemove, arr),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);
}