如何在JavaScript中打印数组中包含指定字符串的所有值
如何打印数组中包含'ing'的元素
给定数组:
let words = ['bring','constant','bath','spring','splashing']
下面是两种简单的实现方式:
方法一:先筛选再打印
用filter()方法先把包含'ing'的元素挑出来,再逐个打印:
let words = ['bring','constant','bath','spring','splashing']; // 筛选出所有包含'ing'的元素 const ingWords = words.filter(word => word.includes('ing')); // 遍历打印每个符合条件的元素 ingWords.forEach(word => console.log(word));
运行后会输出:
bring spring splashing
方法二:遍历数组时直接判断打印
不需要额外生成新数组,遍历原数组的同时检查并打印:
let words = ['bring','constant','bath','spring','splashing']; for (const word of words) { // 检查当前元素是否包含'ing' if (word.includes('ing')) { console.log(word); } }
这个方法的输出和上面完全一致。
补充说明
includes()是字符串方法,用来判断当前字符串是否包含指定的子串,返回布尔值。- 如果需要兼容更老的浏览器(不支持
includes()),可以用indexOf()替代:word.indexOf('ing') !== -1,效果完全相同。
内容的提问来源于stack exchange,提问作者D'Angelo
相关产品推荐
相关产品推荐

