将数组的元素乘以3个加权因子,然后重复



我希望能够将每个数组元素乘以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]

当然,上述功能是不可持续的,所以有更好的方法吗?

您可以通过使用长度为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);

您只需映射输入,然后将其乘以基于其索引的权重。然后,我们可以使用余数运算符将索引保持在权重数组的范围内。

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);

您可以循环遍历数组元素,并使用模运算符根据位置乘以右因子。

模解释
计算余数。

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));

相关内容

最新更新