【发布时间】:2021-01-19 08:23:37
【问题描述】:
我希望能够将每个数组元素乘以 3 个不同的加权因子。
用户输入 = [24,3,0, 56,43,34]
输出 = 24x7,3x3,0x1 + 56x7, 43x3, 34x0.. 并在数组的每 3 个元素处重复一次,然后乘以 7,然后乘以 3,然后乘以 0。
看起来像这样:
对于每个数组元素,乘以每个数组权重因子,并在到达第三个元素时重复
function multiplyWeightFact(input){
const weighting = [7,3,1]
for (let i = 0; i < input.length ; i++) {
console.log( input[0] * weighting[0])
console.log( input[1] * weighting[1])
console.log( input[3] * weighting[2])
break
}
for (let index = 0; index < input.length; index++) {
console.log( input[4] * weighting[0])
console.log( input[5] * weighting[1])
console.log( input[6] * weighting[2])
break
}
}
来自用户的输入 = [24,3,0, 56,43,34]
如果我们有一个包含 100 个数字的数组,它会继续..
输出需要类似于:
resultOutput = 374 when input is [24,10]
当然,上述功能是不可持续的,那么有更好的方法吗?
【问题讨论】:
-
你想要什么输出?
-
输出 = 24x7,3x3,0x1 + 56x7, 43x3, 34x0 (这些是示例数字,但基本上以元素 0 开头的数组中的每个元素都必须乘以 7,然后乘以 3,然后乘以 0然后 + 数组中接下来的 3 个元素,它们再次乘以 7,然后是 3,然后是 0,并以重复模式继续 3elementsxweightingfactor7,3,1 - 所以输出是这些元素的总和乘以重复模式中的权重因子
-
你还没有真正回答这个问题。
input = [24, 3, 0, 56, 43, 34]; weighting = [7, 3, 1]的输出应该是什么样的?它是您评论中的字符串(24x7,3x3,0x1 + 56x7, 43x3, 34x0)吗?或者它是一个带有数字的数组?那么他们应该遵循什么规则呢?或者它是一个数字(数学运算的结果)? -> minimal reproducible example -
看起来像一个数字 - 当输入为 [24,10] 时 resultOutput = 374
-
请将此添加到您的问题中。如您所见,到目前为止所有答案都没有返回预期结果,因为您没有在在您的问题中提到它。
标签: javascript arrays for-loop