如何从数组中删除一个特定值? 类似 :
array.remove(value);
制约:我必须使用核心 JavaScript 。 框架不允许 。
如何从数组中删除一个特定值? 类似 :
array.remove(value);
制约:我必须使用核心 JavaScript 。 框架不允许 。
当前回答
如果您使用现代浏览器, 您可以使用. 过滤器 。
Array. prototype. remove = 函数 (x) { 返回此. filter( 函数 (v) { 返回 v $ ylexx; } ; } ; var a = ["a", b", c"]; var b = a. remove ('a' );
其他回答
Array.prototype.removeItem = function(a) {
for (i = 0; i < this.length; i++) {
if (this[i] == a) {
for (i2 = i; i2 < this.length - 1; i2++) {
this[i2] = this[i2 + 1];
}
this.length = this.length - 1
return;
}
}
}
var recentMovies = ['Iron Man', 'Batman', 'Superman', 'Spiderman'];
recentMovies.removeItem('Superman');
您可以使用
Array.splice(index);
大部分答案都用...
循环的索引和组合删除过滤器
虽然所有解决方案都应该采用这些方法,但我想我们可以使用弦操纵。
需要注意的关于这一解决办法的要点 -- --
这将在数据中留下漏洞( 可以通过额外的过滤器将其移除 ) 此解决方案不仅适用于原始搜索值, 也适用于对象 。
诀窍是...
字符串字符串返回分隔符上的分解数据,以空字符串替换输入数据集中的搜索值。
remove = (input, value) => {
const stringVal = JSON.stringify(value);
const result = JSON.stringify(input)
return result.replace(stringVal, "").split(",");
}
本文创建了一个测试对象和数字的 JSF 中心- https://jsfidle.net/4t7zhkce/33/
检查小提琴中的移除方法 。
[2,3,5].filter(i => ![5].includes(i))
从字符串阵列中查找和删除一个特定的字符串:
var colors = ["red","blue","car","green"];
var carIndex = colors.indexOf("car"); // Get "car" index
// Remove car from the colors array
colors.splice(carIndex, 1); // colors = ["red", "blue", "green"]
资料来源:https://www.codegrepper.com/?search_term=remove+a+particulate+element+ from+array? 来源:https://www.codegrepper.com/?search_term=remove+a+partical+element+ from+array