Created
July 10, 2024 03:16
-
-
Save nodahikaru/287f043db1757ed1817dafdd3a69cedb to your computer and use it in GitHub Desktop.
computeTotal function review
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
The computeTotal function has a couple of issues: | |
Arrow Function and this Context: | |
Issue: Arrow functions do not bind their own this value, so this inside the each callback refers to the outer this (which is the global object in this case) instead of the current DOM element. | |
Solution: Use a regular function expression to correctly bind this. | |
Parsing Errors: | |
Issue: The parseInt function might fail silently if the text content cannot be converted to a number. | |
Solution: Ensure that the text content is a valid number before adding it to the total. | |
Here is the corrected code: | |
function computeTotal() { | |
let total = 0; | |
console.log($("li")); | |
$("li").each(function() { | |
total += parseInt($(this).text(), 10) || 0; | |
}); | |
$("#total").text(`Total: ${total}`); | |
} | |
document.addEventListener("DOMContentLoaded", function(){ | |
computeTotal(); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment