Esta es mi primera pregunta porque soy nuevo en la codificación.
Quiero usar .map para obtener cadenas de una matriz.
let root_vegetables = ['potato', 'taro', 'sweet potato', 'carrot'] let trueRoots = root_vegetables.map((roots) => { if (roots == 'carrot' && 'sweet potato') { return 'True Roots'; } return 'Modified Roots'; }) console.log(trueRoots);entonces mi respuesta esperada es.
['Modified Roots', 'Modified Roots', 'True Roots', 'True Roots']¿Hay alguna forma de hacer esto?
Simplemente puede lograr esto con una sola línea de código usando || operador en lugar de && junto con el operador ternario.
let root_vegetables = ['potato', 'taro', 'sweet potato', 'carrot'] let trueRoots = root_vegetables.map(roots => (roots === 'carrot' || roots === 'sweet potato') ? 'True Roots' : 'Modified Roots') console.log(trueRoots);Parece que la condición de su declaración if es incorrecta. Estás haciendo (roots == 'carrot' && 'sweet potato') , que no funcionará porque necesitas tener otra condición después de la operación AND ( && ) y no un valor, ya que solo devolverá verdadero (El instrucción después de AND, no de la condición if)
Entonces puedes cambiar roots == 'carrot' && 'sweet potato' a roots == 'carrot' || roots == 'sweet potato' . Tenga en cuenta que cambiamos la condición de AND a OR.
Pero también puedes hacer:
// We use the const keyword instead of let if we don't change the value // We use true_roots array to do the checking const true_roots = ['carrot', 'sweet potato'] const root_vegetables = ['potato', 'taro', 'sweet potato', 'carrot'] // We loop through the root_vegetables array and for each value // we check if its in the true_roots array using the .includes method // If its included, we return 'True Roots' // else return 'Modified Roots' // The code inside the map function is just shorthand/syntactical sugar const trueRoots = root_vegetables.map((roots) => (true_roots.includes(roots) ? 'True Roots' : 'Modified Roots')) console.log(trueRoots);Manteniendo su código casi igual, también puede hacerlo así:
let root_vegetables = ['potato', 'taro', 'sweet potato', 'carrot'] var roots = []; for (var i = 0; i < root_vegetables.length; i++) { roots[i] = 'Modified Roots'; if (root_vegetables[i] == 'carrot' || root_vegetables[i] == 'sweet potato') { roots[i] = 'True Roots' } } console.log(roots)