【问题标题】:Check if string is starting with prefix检查字符串是否以前缀开头
【发布时间】:2018-10-31 23:24:13
【问题描述】:

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

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

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

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

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

【问题讨论】:

  • 使用indexOf,而不是lastIndexOf
  • 语法错误,最后缺少)
  • 我看不出该错误的任何原因。如果您忘记在prefix 周围加上引号,您会得到它。
  • 我投票决定将其作为一个简单的印刷错误关闭。唯一的问题似乎是forEach 上缺少右括号。
  • @ggorlen 这可能是复制错误,不会导致他所说的错误。

标签: javascript arrays string if-statement prefix


【解决方案1】:

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

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 添加了解释并添加了您来自 cmets 的建议。
  • 我没有看到有关问题所在以及您如何解决问题的说明。看起来你真正做的只是添加缺少的),这可能只是一个复制错误。
  • 谢谢你们,我认为它与我的其余代码有关,它是单独工作的,但是一旦我将它放入我的代码中,我再次收到此错误(索引):88 Uncaught TypeError: element .indexOf 不是函数 at (index):88 at Array.forEach () at window.onload ((index):86)
  • 刚刚检查过,是的,我的数组没有存储我定位的字符串...再次感谢您的调查。
  • @Barmar 这是她的代码中唯一的错误。这是微不足道的,所以没有费心把它。但是,您提供了最佳解决方案,因此通过您的建议的回答进行了更新。
【解决方案2】:

尝试在函数中使用双引号而不是像这样的“前缀”这样的单引号。

【讨论】:

  • 为什么会有不同?单引号和双引号在 JavaScript 中是可以互换的。
猜你喜欢
  • 1970-01-01
  • 2012-04-05
  • 2012-02-06
  • 2023-01-01
  • 2011-05-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多