Intento deshacerme de un feo método de evaluación de javscript (porque todos sabemos que no es seguro). Tengo el siguiente problema. Construyo una cadena de búsqueda dinámica. Depende del TLD que un usuario decidió buscar.
Aquí está mi código:
if (tld == 0) { var searchString = 'value.tld != ""'; } if (tld == 1) { var searchString = 'value.tld == "de"'; } if (tld == 2) { var searchString = 'value.tld == "com" || value.tld == "net" || value.tld == "org" || value.tld == "info" || value.tld == "biz"'; } if (tld == 3) { var searchString = 'value.tld == "io"'; }Dependiendo del parámetro de búsqueda 'cadena de búsqueda', construyo esta rutina con eval:
if (eval(searchString)) { // Do something special, depends on the tld variable }¿Cómo puedo reconstruir esto sin usar 'eval'? La premisa es que la primera parte del código no se toca.
Gracias por adelantado
Mella
Qué tal si:
let choices = { 1: ['de'], 2: ['com', 'net', 'org', 'info', 'biz'], 3: ['io'] }; function check(tldparam) { if (tld === 0) { return value.tld !== ""; } else { return tld === tldparam && choices[tldparam].includes(value.tld); } }Y lo probamos como:
// Got this value from somewhere let tld = 2; let value = {tld: 'net'}; // This is my checking criterion let tldparam = 2; if (check(tldparam)) { // Do something special, depends on the tld variable }¿Sirve para tu propósito?