如何在JavaScript中遍历并累加像素值?
在JavaScript中遍历数组并累加像素值
针对你给出的数组,我们需要先提取每个元素width属性中的数值部分,累加后再拼接回px后缀,以下是几种常用的实现方式:
方法一:使用reduce(最简洁的数组累加方式)
reduce方法天生适合做数组累加操作,代码简洁高效:
let testArray = [{width: '150px'}, {width : '150px'}]; // 累加数值部分 const totalNum = testArray.reduce((sum, current) => { // 提取width中的数字并转为整数,第二个参数10指定十进制解析 const pixelNum = parseInt(current.width, 10); return sum + pixelNum; }, 0); // 初始累加值设为0 // 拼接成带px的结果字符串 const totalWidth = `${totalNum}px`; console.log(totalWidth); // 输出 "300px"
方法二:使用forEach循环(直观易懂)
如果更习惯遍历的写法,forEach也是不错的选择:
let testArray = [{width: '150px'}, {width : '150px'}]; let totalNum = 0; testArray.forEach(item => { // 用parseFloat可以兼容小数像素(比如"150.5px") const pixelNum = parseFloat(item.width); totalNum += pixelNum; }); const totalWidth = `${totalNum}px`; console.log(totalWidth); // 输出 "300px"
方法三:使用普通for循环(兼容性最佳)
如果需要兼容极低版本的浏览器,普通for循环是最稳妥的:
let testArray = [{width: '150px'}, {width : '150px'}]; let totalNum = 0; for (let i = 0; i < testArray.length; i++) { // 通过replace去掉px后缀,再转为数值 const pixelNum = Number(testArray[i].width.replace('px', '')); totalNum += pixelNum; } const totalWidth = `${totalNum}px`; console.log(totalWidth); // 输出 "300px"
额外注意事项
如果数组中可能存在无效的width值(比如非px格式、空值),可以加入判断避免出错:
const totalNum = testArray.reduce((sum, current) => { const pixelNum = parseInt(current.width, 10); // 只累加有效的数值 if (!isNaN(pixelNum)) { sum += pixelNum; } return sum; }, 0);
内容的提问来源于stack exchange,提问作者S Techie
相关产品推荐
相关产品推荐

