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

Acd*_*cdn 3 javascript arrays string if-statement prefix

我想用javascript检查数组项是否以“前缀”一词开头。

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

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

array.forEach(function(element) {
      if (element.lastIndexOf('prefix', 0) == 0) {
        console.log('prefix');
      }
    }
Run Code Online (Sandbox Code Playgroud)

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

Pri*_*jee 5

这个有效(检查代码上的注释):

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);
   }
});
Run Code Online (Sandbox Code Playgroud)

  • 我没有看到对错误的解释以及您如何修复它。看起来你真正做的只是添加了缺失的`)`,这可能只是一个复制错误。 (2认同)