我想创建一个在数组中查找特定名称 (Inger) 的函数,然后删除该名称。然后我希望函数告诉数组中不存在名称。
var femaleName = ["Anne","Inger","Kari","Marit","Ingrid"]
function removeElement (aTable, aName) {
for (var i = 0; i <= aTable.length - 1; i++) {
if (aTable[1] === aName) {
aTable.splice(i, 1)
document.write(aTable); {break;}
} else if (aTable[i] !== aName) {
document.write(aName + " is not in the list");
}
}
}
我尝试过用这种方法解决这个问题,但还是不行。输出应该是这样的:
Anne, Kari, Marit, Ingrid
Victoria is not in the list
最佳答案
一定要写函数吗? Javascript 有 Array 方法来为您执行此操作。
The filter() method creates a new array with all elements that pass the test implemented by the provided function.
The includes() method determines whether an array includes a certain element, returning true or false as appropriate.
var femaleName = ["Anne", "Inger", "Kari", "Marit", "Ingrid"]
femaleName = femaleName.filter(name => name !== 'Inger')
console.log(femaleName);
console.log(femaleName.includes('Inger'));
关于javascript - 如何使用 for 循环和拼接来删除单词,然后检查数组中的特定单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53345163/