试图在数组Javascript的过滤函数中为IndexOf使用确切的字符串

问题描述 投票:0回答:1

我目前正在使用json数组的过滤器选项创建搜索功能:

if (ploc != " - " ) {
    var filteredarray7 = filteredarray6.filter(function(orte){
        return orte['Painting Location'].indexOf(ploc) !== -1 ;
    });
} else {
    var filteredarray7 = filteredarray6;
}

变量ploc可以是1到12之间的数字,或者字符串“-”,['Painting Location']可以是诸如“ 1; 2; 4; 12;”,“ 1”或“ 3; 5; 12“,而该字符串中的每个数字都类似于绘画位置的类别。

我的问题:我需要做哪些更改,它返回所有在字符串中包含例如1的对象,但不返回包含10、11、12的对象,除非1也是字符串的一部分。

对不起,我的英语不好,我用外语写东西已经很久了。

javascript arrays json filter indexof
1个回答
0
投票

如果我对您的理解正确,则最好使用正则表达式。

return orte['Painting Location'].search(new Regexp('(^|;)\s*' + ploc + '\s*($|;)')) != -1;

或:

return !!orte['Painting Location'].match(new Regexp('(^|;)\s*' + ploc + '\s*($|;)'));

阅读有关JavaScript中RegExp的信息。

© www.soinside.com 2019 - 2024. All rights reserved.