如何从数组中删除一个特定值? 类似 :
array.remove(value);
制约:我必须使用核心 JavaScript 。 框架不允许 。
如何从数组中删除一个特定值? 类似 :
array.remove(value);
制约:我必须使用核心 JavaScript 。 框架不允许 。
当前回答
一位朋友在互联网探索者8号上出了问题, 并向我展示了他的所作所为。 我告诉他这是错的, 他告诉我他得到了答案。 当前的顶尖答案不会在所有浏览器中有效( 比如互联网探索者8号) , 并且它只会消除项目的首次出现。
从数组中删除所有实例
function removeAllInstances(arr, item) {
for (var i = arr.length; i--;) {
if (arr[i] === item) arr.splice(i, 1);
}
}
它会从数组向后循环( 因为随着项目被删除, 指数和长度会变化) , 如果找到的话, 它会删除它。 它会在所有浏览器中发挥作用 。
其他回答
const arr = [1, 2, 3, 4, 5]
console.log(arr) // [ 1, 2, 3, 4, 5 ]
假设你想从Arr删除3号
const newArr = arr.filter(w => w !==3)
console.log(newArr) // [ 1, 2, 4, 5 ]
您可以从数组中添加一个原型函数来“ 移除” 元素 。
以下示例显示当我们知道一个元素的索引时, 如何简单地从数组中删除一个元素。 我们用它来使用 Array. filter 方法 。
Array. prototype. removeByIndex = 函数 (i) {如果 (! Number. is Integer(i) {i < 0) {/ i 必须是一个整数返回它;} 返回此. filter( f, indx) { indx! = i)} var a = [5, - 89, 2 * 2, " some string", null, froid, 未定义, 20, null, 5]; var b = a. remove ByIndex(2); control.log(a); control.log(b);
有时候我们不知道元素的索引
Array. prototype. remove = 函数 (i) { 返回此. filter (f \ \ f \ f y = i) {var a = [5, - 89, 2 ( 2 * 2), “ 一些字符串 ” 无效, 错误, 未定义, 20, 无效, 5] ; var b = a. remove(5). remove (null); 控制台. log (a); 控制台. log (b) / 它消除了所有搜索值的发生次数 。
但是,当我们只想要删除搜索值的首次出现时, 我们可以在函数中使用 Array. indexof 方法 。
Array. prototype. removeFirst = 函数 (i) {i = this.indexof (i); if (! Number. is Integer (i) {i < 0) {返回此 ;} 返回此. filter (f, indx) { indx = indx ! = i)} var a = [5, - 89, 2 * 2, " some string", null, fraud, 未定义, 20, null, 5]; var b = a.remove First(5).remove First(nell); translavor.log(a) ; controad.log(b);
这是我的简单的代码, 用来使用 复数法删除数组中的具体数据。 复数法将给两个参数。 第一个参数是起始数, 第二个参数是删除Count。 第二个参数用于删除从第一个参数值开始的某个元素 。
let arr = [1, 3, 5, 6, 9];
arr.splice(0, 2);
console.log(arr);
您可以使用 JavaScript 的标准 __ proto__ 来定义此函数。例如,
让数据 = [;] 数据 .__proto__.remove = (n) { {数据 = 数据 : blockMap ((v) ) { { 返回 v ? v : [] n? v ; 数据 = [1, 2, 3] ; 数据 = [1, 2, 3] ; 数据.remove (2); 控制台.log(数据); / / [1,3] 数据 = [a', b', c'] ; 数据.remove ('b'); 控制台.log(数据); // [a, c]
最基本的解决办法是:
array.key = null;