javascript - 过滤以 JS 开头的值
问题描述
我尝试搜索一个值是否作为第一个单词存在。例如:“我的名字是詹姆斯”,如果我搜索“nam”=> true,如果我搜索“ja”=> true,如果我搜索“ame”则为 false。它的逻辑有效,但我最后没有收到任何物品。
let text = 'ame';
let option_location = [
{"text": "James"},
{"text": "Valkar"},
{"text": ""},
{"text": "James2"},
];
// This works but not as I wanted
let itemsLocation = '';
itemsLocation = option_location.filter(item => item.text.includes('ame'));
console.log('Values', itemsLocation);
// This is not working
let itemsLocation2 = '';
itemsLocation2 = option_location.filter(item =>{
item.text = item.text.toLowerCase();
let words = item.text.split(" ");
words.forEach((element,index) => {
if(element.startsWith(text)){
return true;
}else{
return false;
}
});
});
console.log('Values', itemsLocation2);
解决方案
原因是您使用startswith()
了检查单词是否以给定字符串开头的函数,该字符串显然name
不以ame
.
而James
开始于ja
并name
开始于nam
该includes()
函数只检查单词是否包含给定的字符串,无论它在哪里。
推荐阅读
- javascript - Can I Use Google Apps Script to Get the List Preset From One Paragraph and Apply it to Another in Google Slides
- javascript - 将异步函数保存为字符串或数据结构以获取其文本以显示在我的浏览器上
- javascript - Storing Images on SQL With Node Js
- javascript - Immediately stop jQuery animate positioning animation
- flask-sqlalchemy - Assiging query value to another model AttributeError: 'BaseQuery' object has no attribute
- docker-networking - Can a docker-based application participate in link-level routing protocol such as OSPF (specifically Anycast)?
- exoplayer2.x - Change playback speed in exoplayer
- ios - How can I access a binary framework in the GitHub Release with SPM when the repo is private?
- java - 如何下载leakcanary-android aar文件
- php - PHP script returns success but does not save a new row in MySQL