仅当另一个数组中存在空元素时,我才想从数组中删除元素。我有这个:
var fruits = ["Banana", "Naranja", "Manzana", "Mango", "Fresa", "Limón", "Lima", "Sandia"];
var vegetales = ["", "Ajo", "", "Cebolla", "Tomate", "", "", "Zanahoria"];
// The output should be this:
// ["Naranja", "Mango", "Fresa", "Sandia"]
function myFunction() {
for (var i in vegetales) {
if (vegetales[i] == '') {
frutaAeliminar = fruits[i];
indexFruta = fruits.indexOf(frutaAeliminar);
if (indexFruta != -1) {
fruits.splice(indexFruta, 1)
}
}
}
console.log(fruits);
}
myFunction();
最佳答案
使用 ES6 的示例
使用Array.filter在三元中使用 &&
可以让我们在不需要时不必担心 else
const fruits = ["Banana", "Naranja", "Manzana", "Mango", "Fresa", "Limón", "Lima", "Sandia"];
const vegetales = ["", "Ajo", "", "Cebolla", "Tomate", "", "", "Zanahoria"];
/* only pick if corresponding array item does not equal '' */
const newArray = fruits.filter((fruit, idx) => (vegetales[idx] !== '' && fruit))
console.log(newArray)
关于javascript - 根据另一个数组的空元素从一个数组中删除元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43835251/