# 创建乘积数组|博客系列

> 本文详细讲解如何在不使用除法的情况下，基于给定数组构建乘积数组B，使每个B[i]等于原数组A中除A[i]外所有元素的乘积，并提供了高效的JavaScript实现与思路分析，适合面试和算法学习。

- 原文：https://feinterview.poetries.top/docs/fe-blog-docs/blog-docs/data-struct/31-%E5%88%9B%E5%BB%BA%E4%B9%98%E7%A7%AF%E6%95%B0%E7%BB%84
- 来源：前端进阶之旅（feinterview.poetries.top）
- 更新：2025.10.25

---

### 题目描述

 给定一个数组A`[0,1,...,n-1]`,请构建一个数组B`[0,1,...,n-1]`,其中B中的元素`B[i]=A[0]*A[1]*...*A[i-1]*A[i+1]*...*A[n-1]`。不能使用除法 

### 解题思路

正常来说，看到这个题目，首先想到的是`B[i]`中的值为`A`中所有数的乘积再除以`A[i]`，但题目规定了不能用除法。

所以换一种思路，我们将`B[i]`的每个值都取出来，如下图：

![array1](https://hexo-blog-1256114407.cos.ap-shenzhen-fsi.myqcloud.com/array1.png)

如图，`B`中每一项的值为每一行的乘积；

所以我们可以分别求出下半个三角形和上半个三角形，然后乘积即为数组`B`

### coding

```javascript
function multiply (array) {
    const result = []
    if (Array.isArray(array) && array.length > 0) {
        result[0] = 1;
        for(let i = 1; i < array.length; i++) { // 计算下半三角形
            result[i] = result[i - 1] * array[i - 1]
        }
        let temp = 1;
        for (let j = array.length - 2; j >= 0; j--) { // 计算上半三角形并乘以之前的下半三角形
            temp = temp * array[j + 1] // 上半三角形的每一项
            result[j] = temp * result[j]
        }
    }
    return result
}
```

**测试代码**

```javascript
console.log(multiply([1, 2, 3, 4]))
// [24, 12, 8, 6]
```
