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

3
我希望用JavaScript检查数组项是否以单词“prefix”开头。
到目前为止,我已经做了以下事情:

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

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

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


2
使用indexOf,而不是lastIndexOf - undefined
1
你有一个语法错误,你在结尾处缺少了) - undefined
1
我看不出那个错误的原因。如果你忘记在 prefix 周围加上引号,你就会遇到这个问题。 - undefined
1
我投票关闭这个问题,因为这只是一个简单的打字错误。唯一的问题似乎是forEach缺少了一个闭合括号。 - undefined
@ggorlen 这很可能是一个复制错误,它不会导致他所说的错误。 - undefined
当然,但是代码中没有任何错误,所以看起来问题已经解决或者是无法再现的。 - undefined
2个回答

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

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);
   }
});


@Barmar 在评论中添加了解释并采纳了您的建议。 - undefined
2
我没有看到对问题出在哪里以及你是如何修复的解释。看起来你只是简单地添加了缺失的 ),这可能只是一个复制错误。 - undefined
谢谢你们两个,我觉得这与我的代码的其他部分有关,它在单独运行时是正常的,但一旦放入我的代码中,就会再次出现这个错误(index):88 Uncaught TypeError: element.indexOf不是一个函数 在(index):88 在Array.forEach (<anonymous>) 在window.onload ((index):86) - undefined
刚刚检查了一下,是的,我的数组没有存储我想要的字符串...再次感谢你的帮助。 - undefined
@Barmar 这是她代码中唯一的错误。这个错误很微不足道,所以没有费心去修复它。然而,你提供了最佳解决方案,所以我已经根据你的建议更新了我的答案。 - undefined
@Alinacdn 你能点击投票按钮下方的勾选标记将此问题标记为已解决吗?https://stackoverflow.com/help/someone-answers - undefined

-4

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


6
为什么会有区别呢?在JavaScript中,单引号和双引号可以互换使用。 - undefined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接