我想用 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);
}
});
关于javascript - 检查字符串是否以前缀开头,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53093241/