简体   繁体   中英

Why this Javascript code is behaving asynchronous?

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

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.

  '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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM