如果变量包含,则输出包含的变量

if variable contains, output those that do

本文关键字:包含 变量 输出 如果      更新时间:2023-09-26

我在JS中有一个数据集,我可以指出一个字母是在字符串(来自数据库的单词)中,但我不能设法丢弃不包含该字母的单词,只是输出包含该字母的单词。

data = apple, orange, grape.
user inputs 'p'
if(data contains user input)
{
    output the data that contain the user input.
}

//代码输出= 'apple', 'grape'

//橙色被丢弃,因为它不包含'p'(用户输入)。

上面的Sudo代码,我该怎么做呢?

使用for循环遍历数据,使用indexOf测试匹配

var data = ['apple', 'orange', 'grape'];
var input = 'p';
for (var i = 0; i < data.length; i++) {
    if (data[i].indexOf(input) != -1) {
        console.log(data[i]);
    }
}