检查字符串是否以前缀开头

Check if string is starting with prefix

我想检查 javascript 数组项是否以单词 "prefix" 开头。

到目前为止我做了这样的事情:

let array = ["prefix-word1", "prefix-word2"];

array.forEach(function(element) {
      if (element.lastIndexOf('prefix', 0) == 0) {
        console.log('prefix');
      }
    }

出于某种原因,我一直收到未定义前缀的错误。请帮忙。

这个有效(查看代码注释):

let array = ["prefix-word1", "prefix-word2" , "does not start with prefix"];

array.forEach(function(element) {
   // Check if the first word is prefix
   if (element.indexOf('prefix') == 0) {
     console.log('prefix');
     console.log(element);
   }
});
 
 console.log("Second approach which is not suggested");
 array.forEach(function(element) {
   // not the correct approach as suggested by @Barmar though it works
   if (element.lastIndexOf('prefix',0) == 0) {
     console.log('prefix');
     console.log(element);
   }
});

尝试在函数中使用双引号而不是单引号 "prefix"。