如何从数组中删除一个特定值? 类似 :
array.remove(value);
我必须使用核心核心核心JavaScript。 不允许框架 。
如何从数组中删除一个特定值? 类似 :
array.remove(value);
我必须使用核心核心核心JavaScript。 不允许框架 。
当前回答
const array = [1,2,3,4,5,6,7,8,9,0];
const index = array.indexOf(5);
// find Index of specific number
if(index != -1){
array.splice(index, 1); // remove number using index
}
console.log(array);
let array = [1, 2, 3, 4, 5, 1, 7, 8, 9, 2, 3, 4, 5, 6];
array = array.filter(number=> number !== 5);
console.log(array);
使用合并和拆分
let array = [1, 2, 3, 4, 5, 1, 7, 8, 9, 2, 3, 4, 5, 6]
array = Array.from(array.join("-").split("-5-").join("-").split("-"),Number)
console.log(array)
其他回答
我还有一个从阵列中移除的好办法:
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
通过传递其值来删除项目 --
const remove=(value)=>{
myArray = myArray.filter(element=>element !=value);
}
将项目通过索引编号删除 -
const removeFrom=(index)=>{
myArray = myArray.filter((_, i)=>{
return i!==index
})
}
您可以为此创建一个原型。只需通过数组元素和您想要从数组元素中删除的值:
Array.prototype.removeItem = function(array,val) {
array.forEach((arrayItem,index) => {
if (arrayItem == val) {
array.splice(index, 1);
}
});
return array;
}
var DummyArray = [1, 2, 3, 4, 5, 6];
console.log(DummyArray.removeItem(DummyArray, 3));
删除在索引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);
}
从数组中删除一个特定元素/字符串可在单班条中进行:
theArray.splice(theArray.indexOf("stringToRemoveFromArray"), 1);
此处:
阵列:要从
将字符串从矩阵中移除:要删除的字符串,而1是要删除的元素数量。
注 注 注 注 注注:如果“字符串要从阵列中移除”不位于数组中,这将删除数组的最后一个元素。
在移除该元素之前先检查该元素是否存在于您的阵列中, 总是很好的做法 。
if (theArray.indexOf("stringToRemoveFromArray") >= 0){
theArray.splice(theArray.indexOf("stringToRemoveFromArray"), 1);
}
取决于客户电脑上是否有新版或旧版的剪贴条:
var array=['1','2','3','4','5','6']
var newArray = array.filter((value)=>value!='3');
或
var array = ['1','2','3','4','5','6'];
var newArray = array.filter(function(item){ return item !== '3' });
“ 3” 是您想要从数组中删除的值。 然后, 数组将变成 :['1','2','4','5','6']