触发“调整大小”事件时不会生成新数组

I am trying to generate a new array each the the width of the browser changes. With this purpose, I keep an eye on the width with "resize" event. This event fires out every time the width changes. Hovewer, the new array doesn't get generated every time. Instead a same array is generated all the time. A link to my pen

 var shelfImages = document.querySelector(".shelf-images");
 var wrap = document.querySelector(".wrap");
 var width = document.documentElement.clientWidth;
 var arr = [ "1.jpg", "2.jpg","3.jpg","4.jpg","5.jpg","6.jpg"];

    window.addEventListener("DOMContentLoaded", function() {
       getNumberOfShelves(arr, width);
    });
   window.addEventListener("resize", function() {
      getNumberOfShelves(arr, width);
    });

  function getNumberOfShelves(arra, w) {

    if (w >= 1126) {
      while (wrap.firstChild) {
      wrap.removeChild(wrap.firstChild);
    }
    var numberOfBooks = 4;
    var arrayOfArrays = [];
      for (var i = 0; i < arra.length; i += numberOfBooks) {
         arrayOfArrays.push(arra.slice(i, i + numberOfBooks));
    }  
} else if (w <= 1125 && w >= 583) {
    while (wrap.firstChild) {
       wrap.removeChild(wrap.firstChild);   
}
 var numberOfBooks = 3;
 var arrayOfArrays = [];
       for (var i = 0; i < arra.length; i += numberOfBooks) {
  arrayOfArrays.push(arra.slice(i, i + numberOfBooks));
 }
} else {
while (wrap.firstChild) {
  wrap.removeChild(wrap.firstChild);
}
  var numberOfBooks = 2;
  var arrayOfArrays = [];
      for (var i = 0; i < arra.length; i += numberOfBooks) {
      arrayOfArrays.push(arra.slice(i, i + numberOfBooks));
    }
  }
}
评论
  • 琴和雅
    琴和雅 回复

    You have to update your width in the listener. As of now, width takes on initial value of document.documentElement.clientWidth and never changes. Try logging it in your resize listener to see what I mean.