Javascript 检查数组是否按特定顺序包含特定项
我需要根据输入值更改跨度中字符的背景。但是我必须根据输入值的具体顺序检查条目。例如,如果我输入了“Inv”,我只想更改“Inventory”元素中3个字母的背景,而不是侧边栏中的所有“i”、“n”、“v”条目 这就是我现在所拥有的Javascript 检查数组是否按特定顺序包含特定项,javascript,css,string,dictionary,Javascript,Css,String,Dictionary,我需要根据输入值更改跨度中字符的背景。但是我必须根据输入值的具体顺序检查条目。例如,如果我输入了“Inv”,我只想更改“Inventory”元素中3个字母的背景,而不是侧边栏中的所有“i”、“n”、“v”条目 这就是我现在所拥有的 backgroundColorSetter(item) { const spans = item.name.split("").map((char) => (this.inputCharsArray && this
backgroundColorSetter(item) {
const spans = item.name.split("").map((char) => (this.inputCharsArray && this.inputCharsArray.includes(char)
? this._spanBackgroundSetter(char)
: this._spanNoBackgroundSetter(char)));
return spans;
}
获取每个匹配项的索引。然后,如果对于任何匹配索引
m
,i>=m
和i
(其中l
是匹配的长度),则应突出显示索引i
处的字符:
constmatchstr='Inv';
const str=listItems.name;
// https://stackoverflow.com/questions/2295657/return-positions-of-a-regex-match-in-javascript
const re=new RegExp(matchStr,'gi');//删除i以区分大小写
常量匹配索引=[];
让我们比赛;
while((match=re.exec(str))!==null){
matchindex.push(match.index);
}
常量span=listItem.name.split(“”).map((char,charIndex)=>{
const highlight=matchindex.some(mIndex=>charIndex>=mIndex&&charIndex
为了提高效率,可以根据角色是否匹配提前对其进行分组。那么,您只需要为背景的每次更改设置一个跨度,而不是为每个角色设置一个跨度。谢谢,先生!如何像我在示例中所做的那样将其用于三值呢?如果您只是在地图内部讨论,您可以执行
returnhighlight代码>。另一个选项是完全删除highlight变量,只需执行(char,charIndex)=>匹配索引代码>由于某种原因,在使用它时出现“Aw,Snap”问题。“Aww Snap”是chrome崩溃,对吗?我能想象的唯一一件事是,如果有一个无限循环或其他什么东西——你有什么评论让它重新开始工作?嗯……也许是while循环的问题
const matchStr = 'Inv';
const str = listItems.name;
// https://stackoverflow.com/questions/2295657/return-positions-of-a-regex-match-in-javascript
const re = new RegExp(matchStr, 'gi'); // Remove i to be case sensitive
const matchIndices = [];
let match;
while ((match = re.exec(str)) !== null) {
matchIndices.push(match.index);
}
const spans = listItem.name.split("").map((char, charIndex) => {
const highlight = matchIndices.some(mIndex => charIndex >= mIndex && charIndex < mIndex + matchStr);
// return ...
});