Home > database >  Javascript user input as an actual if statement javascript
Javascript user input as an actual if statement javascript

Time:03-31

I was wondering whether it is possible to take user input as an actual if statement? For example: user wants to find values which are >=100&<200 in an array I'd like to make something like this:

let array = [1,100,200]
let userInput = document.querySelector("#userInput").value // ">=100&<200"

for(let i = 0; i<array.length; i  ){
  if(array[i]&userInput){ // 'array[i]>=100&<200'
    console.log(true);
  }else{
    console.log(false);
  }
}
//result [false,true,false]

CodePudding user response:

let array = [1,100,200]
let userInput = ">=100&<200"

function check(userInput, x) {
  const conditions = userInput.split('&').map(c => `${x}${c}`)
  const conditionsSatisfied = conditions.map(c => eval(c))
  return conditionsSatisfied.reduce((acc,x) => acc&&x)
}

for(let i = 0; i<array.length; i  ){
  if(check(userInput, array[i])){ // 'array[i]>=100&<200'
    console.log(true);
  }else{
    console.log(false);
  }
}

  • Related