真是个新手!我在尝试重新植入一个旋转的图像.基于一系列搜索结果。但确实遇到了令人惊讶的问题。
我正在使用JS/Jquery,并且拥有一个从api中存在的对象数组:
let arrayOfObjects = [
{id: 0, title: 'Beauty & The Beast', img: 'https://imgthing1.com' },
{id: 1, title: 'The Brainiac', img: 'https://imgthing2.com' },
{id: 2, title: 'Mac and Me', img: 'https://imgthing3.com' }
];然后我有了我想要过滤数组的searchTerm,并从以下返回一个新的结果数组:
function checkWords(searchTerm, arr) {
let results = [];
let st = searchTerm.toLowerCase();
// **** i map through the array - if the search term (say its 'a' is the same
// as the first character of an object's 'title'... then it stores
// that object in results, ready to be rendered. ****
arr.map((each) => {
if (st === each.title.charAt(0)) {
results.push(each)
}
})
console.log(finalResults);
}但我想不出如何保持它的匹配..。基于:“比”和“美女与野兽”-传球。“吃”和“美女与野兽”-失败。
发布于 2017-08-26 10:13:44
您可以使用Array#filter并检查字符串是否包含位于零位置的想要的字符串。
let arrayOfObjects = [{ id: 0, title: 'Beauty & The Beast', img: 'https://imgthing1.com' }, { id: 1, title: 'The Brainiac', img: 'https://imgthing2.com' }, { id: 2, title: 'Mac and Me', img: 'https://imgthing3.com' }];
function checkWords(searchTerm, arr) {
let st = searchTerm.toLowerCase();
return arr.filter(each => each.title.toLowerCase().indexOf(st) === 0);
}
console.log(checkWords('bea', arrayOfObjects));
https://stackoverflow.com/questions/45894227
复制相似问题