Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/447.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 检查数组是否按特定顺序包含特定项_Javascript_Css_String_Dictionary - Fatal编程技术网

Javascript 检查数组是否按特定顺序包含特定项

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

我需要根据输入值更改跨度中字符的背景。但是我必须根据输入值的具体顺序检查条目。例如,如果我输入了“Inv”,我只想更改“Inventory”元素中3个字母的背景,而不是侧边栏中的所有“i”、“n”、“v”条目

这就是我现在所拥有的

  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 ...
});