gpt4 book ai didi

javascript - 在一次 JavaScript 迭代中乘以相同数组的值

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:12:31 27 4
gpt4 key购买 nike

在我的问题中,我有一个如下所示的数组

var R = [
{R1 : 1},
{R2 : 2},
{R3 : 3}
];

var L = [
{L1 : 100},
{L2 : 200},
{L3 : 300}
];

我想做成这样

(r1*l2*l3)+(r2*l1*l3)+(r3*l1*l2) / (l2*l3)+(l1*l3)+(l1*l2)

我已经用这段代码在没有盟友的情况下分离了迭代

var x = 1;    
$.each(R, function(index, result_R){
var nilaiR = parseInt(result_R["R"+x]);
var y = 1;
var cross = 0;
$.each(l, function(index, result_L){
if(x != y){
console.log(result_L);
//result is {l2:200},{l3:300},{l1:100},{l3:300},{l1:100}, {l2:200}
}
y++;
})
x++;
})

最佳答案

假设您有可变数量的 R 和 L 项目 (L.length === R.length),这是我使用 Array#reduce 的结果.

为了让我的生活更轻松,我使用了 Array#mapObject#values将对象数组转换为数字数组:

const R = [{R1: 1}, {R2: 2}, {R3: 3}];

const L = [{L1: 100}, {L2: 200}, {L3: 300}];

const r = R.map((o) => Object.values(o)[0]); // convert to array of numbers
const l = L.map((o) => Object.values(o)[0]); // convert to array of numbers

// iterate r and multiply each item by all items in l that don't have the same index, and sum the results
const numerator = r.reduce((sr, vr, ir) => sr + l.reduce(
(sl, vl, il) => il !== ir ? sl * vl : sl, vr
), 0);

// iterate l and sum each multiplied pair
const denominator = l.reduce((s, v, i) =>
s + l.slice(i + 1).reduce((ss, vv) => ss + v * vv, 0), 0);

console.log(numerator / denominator);

如果你总是在 R 中有 3 个项目,在 L 中有 3 个项目,只需将数学公式转换为函数:

const R = [{R1: 1}, {R2: 2}, {R3: 3}];
const L = [{L1: 100}, {L2: 200}, {L3: 300}];

const f = (R, L) => {
const [r1, r2, r3] = R.map((o) => Object.values(o)[0]); // convert to array of numbers, and assign to variables
const [l1, l2, l3] = L.map((o) => Object.values(o)[0]); // convert to array of numbers, and assign to variables

return ((r1*l2*l3)+(r2*l1*l3)+(r3*l1*l2)) / ((l2*l3)+(l1*l3)+(l1*l2));
};

console.log(f(R, L));

和 ES5 版本:

var R = [{R1: 1}, {R2: 2}, {R3: 3}];
var L = [{L1: 100}, {L2: 200}, {L3: 300}];

function convertToNumbers(arr) {
return arr.map(function(o) {
return o[(Object.keys(o)[0])];
});
}

function f(R, L) {
var r = convertToNumbers(R);
var l = convertToNumbers(L);

return ((r[0]*l[1]*l[2])+(r[1]*l[0]*l[2])+(r[2]*l[0]*l[1])) / ((l[1]*l[2])+(l[0]*l[2])+(l[0]*l[1]));
};

console.log(f(R, L));

关于javascript - 在一次 JavaScript 迭代中乘以相同数组的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46549972/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com