统计以下数组包含"a"或"A"的数组元素,把含"a"或"A"的数组元素存放新数组中,并输出控制台。提示:用indexOf 判断是否包含"a"或"A"的字符。fruit = ["America", 'Greece', "Britain", "Canada", "China", "Egypt", "Aekp"];
时间: 2023-06-01 14:02:15 浏览: 92
JS实现判断数组是否包含某个元素示例
代码如下:
```javascript
var fruit = ["America", 'Greece', "Britain", "Canada", "China", "Egypt", "Aekp"];
var newArr = [];
for (var i = 0; i < fruit.length; i++) {
if (fruit[i].indexOf("a") !== -1 || fruit[i].indexOf("A") !== -1) {
newArr.push(fruit[i]);
}
}
console.log(newArr); // 输出 ["America", "Greece", "Canada", "China", "Aekp"]
```
解释:遍历原数组fruit,用indexOf方法判断每个数组元素是否包含"a"或"A",如果包含则将该元素存入新数组newArr中。最后输出新数组newArr。
阅读全文