[英]Javascript: checking if each value of array is included in string?
I have a JS function that creates an array based on the filters the user selects (this part works fine), and then I have another function (below) which loops through this array and should return true if the value is contained in the string and false if not. 我有一个JS函数根据用户选择的过滤器创建一个数组(这部分工作正常),然后还有另一个函数(下面)循环遍历此数组,如果该值包含在字符串和如果不是,则为假。
var testString = "winter casual";
var valArray = ["winter", "casual"];
function filterArray(...values){
for (i=0; i<values.length; i++){
if (testString.includes(values[i])){
console.log(true);
} else {
console.log(false);
}
}
filterArray(valArray);
However, I click 1 filter button to add "winter" to the values array and it returns "true", but then I click another to add casual and it returns false, even though casual is included in the string as well. 但是,我单击了1个过滤器按钮以将“ winter”添加到values数组中,并返回“ true”,但是随后我单击另一个以添加Casual,并返回false,即使字符串中也包含了Casual。 I have console logged values[] to ensure that both "winter" and "casual" are in my array, and they are.
我有控制台记录的值[],以确保“ winter”和“ casual”都在我的数组中,并且也存在。
Replace ...values
with values
as the parameter: 将
...values
替换为values
作为参数:
var testString = "winter casual"; function filterArray(values){ for (i=0; i<values.length; i++){ if (testString.includes(values[i])){ console.log(true); } else { console.log(false); } } } filterArray(['winter']); filterArray(['winter', 'casual']);
I'm not quite sure if this is what you're looking for, as your function doesn't actually return anything, but this is a fairly simple function that might be useful: 我不太确定这是否是您要查找的内容,因为您的函数实际上没有返回任何内容,但这是一个相当简单的函数,可能会有用:
const containsAll = (str, strs) => strs.every(s => str.includes(s)) console.log(containsAll("winter casual", ['winter'])) //=> true console.log(containsAll("winter casual", ['winter', 'casual'])) //=> true console.log(containsAll("winter casual", ['winter', 'casual', 'medium'])) //=> false
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.