Can I compress this code with an array or loop?

Forgive me, I hope this question is not too obvious, I am javascript noob.

I have javascript code that takes numbers from an xml sheet and displays them in td elements on an html page. It works, but I think it can be condensed into an array or loop to be more efficient.

Is there a better way to write this code?

window.onload=function displayPrices() { twentyFourK=(x[i].getElementsByTagName("twentyFourK")[0].childNodes[0].nodeValue); document.getElementById("twentyFourK").innerHTML=toCurrency(twentyFourK); oneOzGold=(x[i].getElementsByTagName("oneOzGold")[0].childNodes[0].nodeValue); document.getElementById("oneOzGold").innerHTML=toCurrency(oneOzGold); fiveOzGold=(x[i].getElementsByTagName("fiveOzGold")[0].childNodes[0].nodeValue); document.getElementById("fiveOzGold").innerHTML=toCurrency(fiveOzGold); tenOzGold=(x[i].getElementsByTagName("tenOzGold")[0].childNodes[0].nodeValue); document.getElementById("tenOzGold").innerHTML=toCurrency(tenOzGold); oneKiloGold=(x[i].getElementsByTagName("oneKiloGold")[0].childNodes[0].nodeValue); document.getElementById("oneKiloGold").innerHTML=toCurrency(oneKiloGold); //etc. } 
+4
source share
3 answers

Yes, a function can make it easier for you:

 window.onload = function() { function loadCurrency(name) { document.getElementById(name).innerHTML = toCurrency(x[i].getElementsByTagName(name)[0].firstChild.nodeValue); } loadCurrency('twentyFourK'); loadCurrency('oneOzGold'); loadCurrency('fiveOzGold'); loadCurrency('tenOzGold'); loadCurrency('oneKiloGold'); }; 

Also, if you have many items to download:

 window.onload = function() { function loadCurrency(name) { document.getElementById(name).innerHTML = toCurrency(x[i].getElementsByTagName(name)[0].firstChild.nodeValue); } var items = ['twentyFourK', 'oneOzGold', 'fiveOzGold', 'tenOzGold', 'oneKiloGold']; items.forEach(loadCurrency); }; 

This requires Array.forEach , which is only available in ECMAScript 5, so there’s a reserve here:

 Array.prototype.forEach = function(action, thisArg) { for(var i = 0, l = this.length; i < l; i++) { if(i in this) { action.call(thisArg, this[i], i, this); } } }; 
+3
source

I would put the currency in my own method. This will be cleaner visually, and will also allow changes in the future:

 window.onload = function displayPrices() { SetCurrency("twentyFourK"); SetCurrency("oneOzGold"); //etc. } function SetCurrency(name) { var elements = x[i].getElementsByTagName(name); if ((elements != null) && (elements.length != 0)) { elements[0].innerHTML = toCurrency(elements[0].childNodes[0].nodeValue); } } 
+1
source

You can create a function with a list of elements in a parameter, and you just need to create a loop going through your list of elements (twenty-four, oneKiloGold, etc.)

0
source

Source: https://habr.com/ru/post/1389851/


All Articles