将逗号分隔的数字相乘为一个数字。

huangapple go评论53阅读模式
英文:

Multiply Comma Seperated number together into one

问题

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

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

我想要的输出是所有数字的乘积。

total = 24;

我正在尝试在JavaScript/jQuery中实现它。有任何帮助吗?

英文:

I m getting values from multiple radio button and storing it into variables as a comma seperated number.

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

output I want is multiplication of of all numbers;

total = 24

I m trying to implement it in javascript/jquery. Any help?

答案1

得分: 3

你可以使用 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);
英文:

You can solve this with split and reduce if you pass in a comma separated string:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

var coef = &quot;1, 2, 3, 4&quot;;

var total = coef.split(&#39;,&#39;).reduce( (a, b) =&gt; a * b );

console.log(total);

<!-- end snippet -->

If you pass in an array, you don't need to split:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

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

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

console.log(total);

<!-- end snippet -->

答案2

得分: 2

以下是翻译好的部分:

你可以尝试类似这样的代码

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

如果数组

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

**演示**

<!-- 开始代码片段js 隐藏true 控制台true Babelfalse -->

<!-- 语言lang-js -->

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

<!-- 结束代码片段 -->

请注意,我只翻译了代码部分,不包括问题或其他内容。

英文:

You could try something like this:

var coef = &quot;1, 2, 3, 4&quot;;
var total = coef.trim().split(&quot;,&quot;).reduce((accumulator, value) =&gt; accumulator * value, 1);

If array

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

Demo

<!-- begin snippet: js hide: true console: true babel: false -->

<!-- language: lang-js -->

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

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年6月19日 17:28:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/76505312.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定