Reputation: 27
I have a html-file, looks like:
...
<div class="colorbox" data-product="oldUpload" data-color="brown" style="background-color: #31261d" title="Brown"></div>
<div class="colorbox" data-product="oldUpload" data-color="cranberry" style="background-color: #6e0a25" title="Cranberry"></div>
...
<div class="colorbox" data-product="TSHIRT" data-color="brown" style="background-color: #31261d" title="Brown"></div>
<div class="colorbox" data-product="TSHIRT" data-color="cranberry" style="background-color: #6e0a25" title="Cranberry"></div>
...
<script src="profiles.js"></script>
And following JavaScript file:
function getSelectedColors() {
let colorboxes = document.getElementsByClassName('colorbox');
let selectedColors = [];
for (let colorbox of colorboxes) {
if (colorbox.classList.contains('checked')) {
selectedColors[colorbox.dataset.product] = (selectedColors[colorbox.dataset.product] || '') + colorbox.dataset.color + ',';
}
}
console.log('Colors:' + selectedColors);
console.log(selectedColors);
return selectedColors;
}
If I run the function getSelectedColors() the output in console is:
Line 1: "Colors: "
Line 2: "[oldUpload: "brown,cranberry,pink,purple,", TSHIRT: "cranberry,...]"
So it seems, the code in function is asynchronous, because "selectedColors" is an empty array directly after for-loop and the function also returns an empty array. But at the moment, I don't understand why, because I think, there's nothing asynchronous in my code.
So why this JS code is behaving asynchronous?
Thanks, Klaus
Upvotes: 0
Views: 73
Reputation: 138257
'Colors:' + selectedColors
Through concatenating the array with a string, the array gets implicitly converted to a string. That will join all the values of the array:
"" + [1, 2, 3] // "1,2,3"
In your case the array is actually empty, it contains no numerical keys.
Upvotes: 0
Reputation: 508
Change
let selectedColors = [];
to let selectedColors = {};
In JS spec arrays only have a numeric index. Other indices are not enumerated and so "invisible" in your console.
Upvotes: 2