英文:
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
你可以使用 split
和 reduce
来解决这个问题,如果你传入一个逗号分隔的字符串:
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 = "1, 2, 3, 4";
var total = coef.split(',').reduce( (a, b) => 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) => 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 Babel:false -->
<!-- 语言: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 = "1, 2, 3, 4";
var total = coef.trim().split(",").reduce((accumulator, value) => accumulator * value, 1);
If array
var total = coef.reduce((accumulator, value) => accumulator * value, 1);
Demo
<!-- begin snippet: js hide: true console: true babel: false -->
<!-- language: lang-js -->
var coef = "1, 2, 3, 4";
var total = coef.trim().split(",").reduce((accumulator, value) => accumulator * value, 1);
console.log(total)
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论