javascript 将逗号分隔的数字相乘为1

q3qa4bjr  于 2023-06-20  发布在  Java
关注(0)|答案(2)|浏览(115)

我从多个单选按钮中获取值,并将其存储到变量中,作为逗号分隔的数字。

var coef = "1, 2, 3, 4";

我想要的输出是所有数字的乘法;

total = 24

我尝试在javascript/jquery中实现它。有什么帮助吗?

cgfeq70w

cgfeq70w1#

如果传入一个逗号分隔的字符串,你可以用splitreduce来解决这个问题:

var coef = "1, 2, 3, 4";

var total = coef.split(',').reduce( (a, b) => a * b );

console.log(total);

如果传入一个数组,则不需要拆分:

var coef = [1, 2, 3, 4];

var total = coef.reduce( (a, b) => a * b );

console.log(total);
fnvucqvd

fnvucqvd2#

你可以尝试这样的东西:

var coef = "1, 2, 3, 4";
var total = coef.trim().split(",").reduce((accumulator, value) => accumulator * value, 1);

If数组

var total = coef.reduce((accumulator, value) => accumulator * value, 1);

Demo

var coef = "1, 2, 3, 4";
var total = coef.trim().split(",").reduce((accumulator, value) => accumulator * value, 1);
console.log(total)

相关问题