javascript - 对所有图像的宽度求和
问题描述
我正在尝试获取所有图像宽度的总和。
我试图获取数组中的值,以便我可以计算它们的总和但仍然无法工作,但它确实应该非常简单,我想要的只是图像宽度值的总和。
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!
}
解决方案
您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()
推荐阅读
- c - 在C中将2个字符串相互匹配?
- reactjs - 简单的 React 组件在 Redux 状态更改后不会更新
- c# - 在 c# 中使用 lambda 降序排列数组
- java - 如果 arraylist 为空,如何保存到 shredpreferences?
- python - 将本地时间和时区转换为 UTC?
- go - 从频道片中选择(发送到免费频道)?
- javascript - 如何在每个对象上防止默认值?只有第一个有效
- reactjs - React Formik 将外部按钮单击与 onSubmit 函数绑定
- c# - 将 System.Drawing.Common.Bitmap (.NET Standard 2.0) 传递给期望 System.Dwawing.Bitmap (.NET 4.7.2) 的类
- java - 将 Hadoop 输出存储到本地 mongodb