首页 > 解决方案 > 对所有图像的宽度求和

问题描述

我正在尝试获取所有图像宽度的总和。

我试图获取数组中的值,以便我可以计算它们的总和但仍然无法工作,但它确实应该非常简单,我想要的只是图像宽度值的总和。

componentDidMount() {
    let images = document.querySelectorAll('#draggable img');
    let widths = [];
    images.forEach(each => {
        each.addEventListener("load", () => {
            widths.push(each.width)
        });
    });
    console.log(widths); // this is logging the array!
    const total = widths.reduce(function(a, b){ return a + b; }); 
    console.log("total is : " + total ); // this is crashing!
}

标签: javascriptreactjs

解决方案


widths Array可能是空的(您正在使用加载事件填充它)并且您正在调用 reduce 而没有 initialValue。这将导致错误,请参阅 Array.reduce

你可以这样做:

widths.reduce((acc, width) => (acc + width), 0);

更新 1,基于您的 Codepen 和您的评论。. 加载事件侦听器并不是真正需要的。IE < 9 存在兼容性问题,attachEvent不支持addEventListener. 我会建议使用具有递归功能的计时器。

sumWidths = () => {
  const images = document.querySelectorAll('#draggable img');
  let sum = 0;

  images.forEach(({ width }) => {
    if(!width){ // not width or width 0 means the image has not been fully loaded.
      setTimeout(this.sumWidths, 500) // delay half second to allow image to load and try again;
      return;
    } else {
      sum = sum + width;
    }
  });

  // This function can be created on parent component
  // or use state management library or what ever befit your needs.
  saveImageWidths(sum); // Create this function

  // Or save `sum` to the state of this component!!!!
  this.setState(state => ({ ...state, widthsSum: sum }));
}

componentDidMount() {
  this.sumWidths();
}

更新 2. 使用加载事件侦听器 在您的分叉工作代码笔中获取战利品

function totalImagesWidth() {
  let reportWidth = 0;
  let images = document.querySelectorAll('#imagesContainer img');
  let imagesWidth = [];
  images.forEach(each => {
    each.addEventListener("load", () => {
      imagesWidth.push(each.width);

      if (imagesWidth.length === images.length) {
        reportWidth = (imagesWidth.reduce((a, b) => { return a + b; }, 0));
        showResult(reportWidth);
      }
    });
  });

  function showResult(reportWidth){
    const results = document.createElement("p");
    results.innerHTML = `
      Images: ${images} <br />
      Total images: ${images.length} <br />
      <code>imagesWidth</code> length: ${imagesWidth.length} <br />
      Images widths: ${imagesWidth.toString()} <br />
      <b>SUM: ${reportWidth}</b>`;
    document.body.appendChild(results);
    console.log(imagesWidth);
  }
}

totalImagesWidth()

推荐阅读