esta función debe contar la "a" en una cadena y calcular una relación entre la suma de todas las "a" y la longitud de la cadena. Funciona bien, excepto cuando la cadena está vacía y debe generar "0" en lugar de NaN. Que'
function ratio(statistic) { let charcount = 0 ; for ( let i = 0 ; i < statistic.length ; i++){ if ( statistic[i] == 'a' ){ charcount += 1 ;} } return Math.round(charcount/statistic.length * 100) ; } console.log(ratio('abababaabaaa')); console.log(ratio('')); // 67 // NaN <---- here should be 0Es lo que quiero arreglar, gracias.
Si la estadística como parámetro en la función de proporción es '', statistic.length es 0. Y esto provoca un error matemático porque algo no se puede dividir por 0. Si escribe un código excepcional como el siguiente, funcionará bien.
function ratio(statistic) { let charcount = 0 ; for ( let i = 0 ; i < statistic.length ; i++){ if ( statistic[i] == 'a' ){ charcount += 1 ; } } return (statistic == ''? 0 : Math.round(charcount/statistic.length * 100)) ; }cuando tiene una cadena vacía o una cadena nula, el valor de statistic.length será 0. Por lo tanto, le falta esta verificación en su código, por eso obtiene NaN (No es un número).
function ratio(statistic) { let charcount = 0 ; for ( let i = 0 ; i < statistic.length ; i++){ if ( statistic[i] == 'a' ){ charcount += 1 ;} } // Corrected code here return statistic.length == 0 ? 0 : Math.round(charcount/statistic.length * 100) ; } console.log(ratio('abababaabaaa')); console.log(ratio('')); // 67 // NaN <---- here should be 0Probar:
function ratio(statistic) { let charcount = 0 ; for ( let i = 0; i < statistic.length; i++ ) { if ( statistic[i] == 'a' ) { charcount += 1; } } if (charcount === 0) return 0; // check if there were no a's in the string, if so return 0 return Math.round(charcount/statistic.length * 100) ; } console.log(ratio('bbbbbbbaaa')); console.log(ratio(''));Para evitar tener que dividir por 0, simplemente verificamos si no se encontraron a y, de ser así, devolvemos 0 en ese momento.