Tengo el siguiente código:
let dataList = []; function filli(index, name, words){ dataList[index] = index; dataList[index] = name; dataList[index] = words; } filli(0, "David", "Testing this") filli(1, "John", "My cellphone") console.log(dataList)Me sale en consola lo siguiente:
$ node attempt.js [ 'Testing this', 'My cellphone' ]Y mi resultado esperado en la consola sería:
[[0, "David", "Testing this"], [1, "John", "My cellphone"]] Pero no obtengo eso en la consola, como puede ver, estaba tratando de obtener esos datos en mi función filli , enviando un índice, un nombre y palabras, pero no funciona.
Espero que me puedas ayudar, gracias.
Está anulando los valores existentes cuando hace dataList[index]= ... . Debe agregarlos como una matriz, algo como esto:
let dataList = []; function filli(index, name, words){ dataList[index] = [index, name, words]; } filli(0, "David", "Testing this") filli(1, "John", "My cellphone") console.log(dataList)Está anulando el mismo valor:
let dataList = []; function filli(index, name, words){ dataList[index] = [] // first create new array dataList[index][0] = index; // then assign to proper indexes dataList[index][1] = name; dataList[index][2] = words; } filli(0, "David", "Testing this") filli(1, "John", "My cellphone") console.log(dataList)Idealmente , las funciones deberían devolver un valor que su función no devuelve en este momento. Una solución alternativa sería agregar sus argumentos a una matriz y devolver eso, y luego insertar ese resultado en la matriz dataList .
const dataList = []; function filli(index, name, words){ return [index, name, words]; } dataList.push(filli(0, 'David', 'Testing this')); dataList.push(filli(1, 'John', 'My cellphone')); console.log(dataList);