Sé que hay muchas preguntas como esta aquí, pero me siguen señalando el uso de includes y eso no me funciona por alguna razón.
Objetivo : use una declaración if para averiguar si existe un número en una matriz. (No importa si es jQuery o plan JS)
Intenté usar include pero falló:
testdata = [1,256] testdata.includes(1) #or testdata.includes(256) \\false También intenté usar indexof pero eso también falló:
testdata = [1,256] testdata.indexOf('256') >= 0 \\falseDe hecho, parece que su matriz [1,256] es el primer elemento de la matriz testdata . De hecho, puede ver que testdata es 1.
Debe comprobar si testdata[0].includes(1)
Su matriz son números, pero su argumento .indexOf es una cadena.
El fragmento a continuación funciona bien.
Si necesita verdadero/falso, use un bloque condicional como:
let numberFound = false; if (testdata.indexOf(256)>-1) { numberFound = true; } else { numberFound = false; }En lugar del bloque completo if/else, es más habitual condensar el condicional usando el operador ternario
como esto:
numberFound = (testdata.indexOf(256) > -1) ? true : false) finalmente, si está probando varias entradas, use una función para devolver true/false dependiendo de lo que se le haya pasado:
function numberFound(number,array) { return (array.indexOf(number) > -1) ? true : false; }He modificado el fragmento:
const testdata = [1,256] console.log(testdata.indexOf(256)); console.log("test for 25: ", (testdata.indexOf(25) > -1) ? true : false); console.log("test for 56: ", (testdata.indexOf(56) > -1) ? true : false); console.log("test for 256: ", (testdata.indexOf(256) > -1) ? true : false); function numberFound(number,array) { return (array.indexOf(number) > -1) ? true : false; } console.log("function testing 256:", numberFound(256,testdata)); console.log("function testing 25:", numberFound(25,testdata));No te está funcionando porque lo usas de forma incorrecta. # es el identificador privado en JS. Si usa // en su lugar, funciona.
testdata = [1,256]; console.log(testdata.includes(1)); // or testdata.includes(256)