You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现arrayA与arrayB对应元素相乘后求和(示例:[1,2]×[3,4]得11)

嘿,这个需求其实就是计算两个数组的点积(Dot Product),我给你几个常用编程语言的实现方案,你可以按需选用:

Python 实现

方法1:基础循环(适合新手理解逻辑)

arrayA = [1, 2]
arrayB = [3, 4]
total = 0
for a, b in zip(arrayA, arrayB):
    total += a * b
print(total)  # 输出 11

逻辑很直白:用zip把两个数组的对应元素配对,然后遍历每一对,相乘后累加到总和里。

方法2:一行代码(简洁写法)

arrayA = [1, 2]
arrayB = [3, 4]
total = sum(a * b for a, b in zip(arrayA, arrayB))
print(total)  # 输出 11

用生成器表达式配合sum函数,把循环和求和一步完成,代码更紧凑。

方法3:用numpy库(适合大数据量场景)

如果你处理的是大规模数组,用numpy会更高效:

import numpy as np
arrayA = np.array([1, 2])
arrayB = np.array([3, 4])
total = arrayA.dot(arrayB)
# 或者更简洁的写法:total = arrayA @ arrayB
print(total)  # 输出 11

JavaScript 实现

方法1:基础循环

const arrayA = [1, 2];
const arrayB = [3, 4];
let total = 0;
for (let i = 0; i < arrayA.length; i++) {
    total += arrayA[i] * arrayB[i];
}
console.log(total); // 输出 11

这里直接通过索引遍历数组,前提是两个数组长度相同(你的问题里刚好满足)。

方法2:用reduce函数(函数式写法)

const arrayA = [1, 2];
const arrayB = [3, 4];
const total = arrayA.reduce((sum, a, index) => sum + a * arrayB[index], 0);
console.log(total); // 输出 11

reduce函数可以逐步累加,每次取当前元素和另一个数组对应索引的元素相乘,加到总和里。

注意:如果两个数组长度不一致,这些方法可能会出问题,实际使用时最好先判断两个数组长度是否相等哦!

内容的提问来源于stack exchange,提问作者user8977455

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 03:38:37