我希望能够将每个数组元素乘以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]
当然,上面的功能是不可持续的,所以有没有更好的方法呢?
发布于 2021-01-19 16:30:33
您可以通过获取一个索引和长度为weighting的余数运算符进行映射。
const
multiplyBy = weighting => (v, i) => v * weighting[i % weighting.length],
array = [24, 3, 0, 56, 43, 34],
weighting = [7, 3, 1],
result = array.map(multiplyBy(weighting));
console.log(...result);
使用x
const
multiplyBy = weighting => (v, i) => `${v}x${weighting[i % weighting.length]}`,
array = [24, 3, 0, 56, 43, 34],
weighting = [7, 3, 1],
result = array.map(multiplyBy(weighting));
console.log(...result);
发布于 2021-01-19 16:27:10
您可以遍历数组元素,并使用模运算符根据右因数的位置与之相乘。
模数解释
计算余数。
const weighting = [7, 3, 1] // Instead of 3 weighting.length
1. 0 % 3 = 0 = Array Element = 7
2. 1 % 3 = 1 = Array Element = 3
3. 2 % 3 = 2 = Array Element = 1
4. 3 % 3 = 0 = Array Element = 7
And again ...
function multiplyWeightFact(input) {
const weighting = [7, 3, 1]
for (let index = 0; index < input.length; index++) {
input[index] *= weighting[index % weighting.length];
}
return input;
}
let input = [5,4,3,2,1]
console.log(multiplyWeightFact(input));
发布于 2021-01-19 16:33:38
您可以只对输入进行map操作,然后根据其索引将其乘以权重。然后,我们可以使用remainder operator将索引保持在权重数组的范围内。
function multiplyWeightFact(input, weight){
return input.map((num, index) => num * weight[index % weight.length]);
}
const weight = [7, 3, 0];
const input = [24, 3, 0, 56, 43, 34];
const result = multiplyWeightFact(input, weight);
console.log(result);
https://stackoverflow.com/questions/65787732
复制相似问题