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)
出于某种原因,我不断收到未定义前缀的错误。请帮忙。
这个有效(检查代码上的注释):
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)
| 归档时间: |
|
| 查看次数: |
1358 次 |
| 最近记录: |