JavaScript算法试题系列-01 发表于 2017-06-15 | 更新于 2017-06-15 | 分类于 学习笔记 , JavaScript | | 共 169 字 | 阅读 次 题目要求: 1234567var firstArray = [2, 2, 4, 1];var secondArray = [0, 0, 0, 2];var thirdArray = [-2, -2, -3, 2];productExceptSelf(firstArray); // [8, 8, 4, 16]productExceptSelf(secondArray); // [0, 0, 0, 0]productExceptSelf(thirdArray); // [12, 12, 8, -12] 解答: 123456789101112131415161718192021222324function productExceptSelf(numArray) { var product = 1; var size = numArray.length; var output = []; // From first array: [1, 2, 4, 16] // The last number in this case is already in the right spot (allows for us) // to just multiply by 1 in the next step. // This step essentially gets the product to the left of the index at index + 1 for (var x = 0; x < size; x++) { output.push(product); product = product * numArray[x]; } // From the back, we multiply the current output element (which represents the product // on the left of the index, and multiplies it by the product on the right of the element) var product = 1; for (var i = size - 1; i > -1; i--) { output[i] = output[i] * product; product = product * numArray[i]; } return output;} ------ 本文结束 ------ 版权声明 加州提子面包 by MiG is licensed under a Creative Commons BY-NC-SA 4.0 International License. 由MiG创作并维护的加州提子面包博客采用「创作共用保留署名-非商业性使用-相同方式共享」4.0国际许可证. 本文首发于加州提子面包 博客( https://gihcctpd.github.io ),版权所有,侵权必究.