假设我有一个来自数据库的带有ids的字符串:
string = "3, 4, 5, 8, 16, 2, 43"
和一些复选框中的数值,我映射到一个数组中
filter = ["35", "34"]
我想要比较数组中的所有数字是否都是字符串的一部分,所以我尝试了下面这样的方法(比较有效的方法)
if ( string.indexOf(filter) !== -1 )
{ console.log("numbers of filter are in string") }
但我的问题是3在34中-所以indexOf
是真的。你知道我该怎么比较这个“正确的方式”吗?
发布于 2017-11-04 05:46:58
我的例子。希望能有所帮助
const str = "23, 4, 567, 7",
firstArr = ["1", "3", "4"],
secondArr = str.split(", ");
if(secondArr.filter(e => firstArr.indexOf(e) !== -1).length > 0) {
console.log('str has some numbers from the firstArr');
}
发布于 2017-11-04 05:43:34
您可以很容易地在前面添加一个空格:
const string = " 3, 4, 5, 8, 16, 2, 43",
filters = ["35", "34"];
if(filters.every( filter => string.includes(" "+filter))){
alert(" all found!");
}
或者,您可以从字符串中构建一个实数组:
const string = "3, 4, 5, 8, 16, 2, 43",
filters = ["35", "34"];
const ids = string.split(", ");
if(filters.every( filter => ids.includes(filter)))
alert(" all found!");
发布于 2017-11-04 05:44:16
string.includes(filter)
https://stackoverflow.com/questions/47104769
复制相似问题