Actualmente estoy aprendiendo JS y no estoy muy seguro de lo que esto hace. ¿Podría obtener alguna explicación?
num = num.map(x => { return (x == 0) ? 1: 0; }).join("");Gracias.
map llama a una función callbackFn proporcionada una vez para cada elemento de una matriz, en orden, y construye una nueva matriz a partir de los resultados. callbackFn se invoca solo para los índices de la matriz que tienen valores asignados (incluidos los no definidos).
// Arrow function map((element) => { ... }) map((element, index) => { ... }) map((element, index, array) => { ... }) // Callback function map(callbackFn) map(callbackFn, thisArg) // Inline callback function map(function(element) { ... }) map(function(element, index) { ... }) map(function(element, index, array){ ... }) map(function(element, index, array) { ... }, thisArg)https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map
Entonces, con eso en mente, echemos un vistazo al código JS
num = num.map(x => { return (x == 0) ? 1: 0; }).join("");Para mí, este código está algo incompleto, pero me imagino que podrías tener algo como
let num = [1,2,3,4,5,6,7,8,9,10] num = num.map(x => { return (x == 0) ? 1: 0; }).join(""); // we reassign the value of num to a NEW array, because map will create that for us. // when we call .map() on our array, it will begin to iterate over the array // we're giving each element an arbitrary name of 'x' // In our return statement, we are going to make a comparison with a ternary operator. // We are going to loosely compare each element of the array (x) to zero. // If this is true, we reassign x to 1. If this is false, we reassign to 0 // We then join the array with no separators using Array.prototype.join() // => '0000000000'Entonces ahora si lo hacemos con otro arreglo, veamos que pasa.
let num = [0,0,1,1,4,0,5] num = num.map(x => { return (x == 0) ? 1: 0; }).join(""); // => '1100010'