Soy nuevo en JavaScript y estoy tratando de contar el número de cada alfabeto en bigLettersArr
. Hice un ciclo for para pasar por cada elemento en bigLettersArr
y actualizar el contador, pero de alguna manera no funciona. Nuevamente, todo lo que estoy tratando de hacer es actualizar el contador de objetos del alphabet
para obtener el número de cada letra.
Además, creo que podría haber una forma mucho más inteligente de hacer esto, busqué otros métodos para la matriz, pero no pude encontrar ni encontrar un código mejor.
Aquí está mi código. ¡Gracias por leer esto!
const bigLettersArr = [ "X","E","Q","M","L","L","L","B","X","C","A","F", "X","W","B","W","A","F","D","Z","B","C","L","F", "M","E","B","E","A","M","L","L","B","G","L","G", "H","F","H","G","M","A","F","B","B","C","G","F", "H","Z","B","L","L","H","J","L"] //made an empty array with all alphabet AZ const alphabet = { 'A': 0, 'B': 0, 'C': 0, 'D': 0, ... 'Z':0 } //Count how many each alphabet in the array. for(let letter in bigLettersArr){ let targetLetter = bigLettersArr[letter] // console.log(targetLetter) alphabet.targetLetter += 1 } console.log(alphabet)
Las matrices son iterables en JS. así que simplemente puede usar for..of
loop aquí
Debe usar for..in
loop con objects
y for..of
con arrays
La declaración for...in itera sobre todas las propiedades enumerables de un objeto que están tecleadas por cadenas (ignorando las tecleadas por símbolos), incluidas las propiedades enumerables heredadas.-MDN
La instrucción for...of crea un bucle iterando sobre objetos iterables, incluidos: String integrado, Array, objetos similares a matrices (por ejemplo, argumentos o NodeList), TypedArray, Map, Set y iterables definidos por el usuario. Invoca un gancho de iteración personalizado con declaraciones que se ejecutarán para el valor de cada propiedad distinta del objeto.-MDN
También puede usar forEach
en lugar de for..of
como:
bigLettersArr.forEach(letter => alphabet[letter] += 1);
const bigLettersArr = ["X", "E", "Q", "M", "L", "L", "L", "B", "X", "C", "A", "F", "X", "W", "B", "W", "A", "F", "D", "Z", "B", "C", "L", "F", "M", "E", "B", "E", "A", "M", "L", "L", "B", "G", "L", "G", "H", "F", "H", "G", "M", "A", "F", "B", "B", "C", "G", "F", "H", "Z", "B", "L", "L", "H", "J", "L"] const alphabet = Array .from( { length: 26 }, ( _, i ) => String.fromCharCode( i + 65 )) .reduce( ( acc, curr ) => ( ( acc[curr] = 0 ), acc ), {} ); for ( let letter of bigLettersArr ) { alphabet[letter] += 1 } console.log( alphabet )
/* This is not a part of answer. It is just to give the output full height. So IGNORE IT */ .as-console-wrapper { max-height: 100% !important; top: 0; }
Está intentando incrementar la propiedad targetLetter
.
En su lugar, utilice la notación de corchetes:
for (let letter in bigLettersArr) { let targetLetter = bigLettersArr[letter] alphabet[targetLetter] += 1 }
mi manera...
const bigLettersArr = [ 'X', 'E', 'Q', 'M', 'L', 'L', 'L', 'B', 'X', 'C' , 'A', 'F', 'X', 'W', 'B', 'W', 'A', 'F', 'D', 'Z' , 'B', 'C', 'L', 'F', 'M', 'E', 'B', 'E', 'A', 'M' , 'L', 'L', 'B', 'G', 'L', 'G', 'H', 'F', 'H', 'G' , 'M', 'A', 'F', 'B', 'B', 'C', 'G', 'F', 'H', 'Z' , 'B', 'L', 'L', 'H', 'J', 'L' ] const alphabet = Object.fromEntries(Array.from({length:26},(_,i)=>[String.fromCharCode('A'.charCodeAt(0)+i),0])) bigLettersArr.forEach( letter => { alphabet[letter]++ }) console.log( alphabet )
.as-console-wrapper { max-height: 100% !important; top: 0 }