在Javascript中动态地将条件放入if块中



有没有一种方法可以让我们动态地在"if"根据用户输入阻塞?

: -

const filter
if (location === true) { // location is user input 
filter = first condition
}
if (skill === true) { // skill is user input 
filter = second condition
}
if (filter) {
/* filter contains dynamic value if location is true then filter should contain first condition, if skill is 
true filter should contain second condition and if both are two true then filter should contain both conditions*/
console.log("Hello")
}

您可以在if语句中计算条件,然后将比较结果赋值给filter:

const input = 'a';
var filter
if (input === 'a') {
filter = 1 == true; //first condition
}else if (input === 'b') {
filter = 0 == true; //second condition
}
if (filter) {
console.log("Hello")
}

我们需要重命名位置,但您可能需要其中一个或多个?

const filter = []
let loc = true;
let skill = false;
if (loc) filter.push("location") 
if (skill)  filter.push("skill") 
// show
if (filter.length) { // more than 0 items
filter.forEach(item => console.log(item))
}
if (filter[0] === "skill") console.log("only skill")
else if (filter.length===1 && filter[0] === "location") console.log("only location")
else if (filter.length == 2) console.log("both")

最新更新