gpt4 book ai didi

javascript - 如何在 Javascript 中将数字拆分成数字?

转载 作者:行者123 更新时间:2023-11-30 07:23:11 24 4
gpt4 key购买 nike

我想将一个数字拆分成它的数字(例如 4563 到 4 、 5 、 6 、 3 )然后沉迷于这个数字。 (例如:4+5+6+3=18)

我可以分别为 3 位或 2 位和...数字编写代码,但我不能为每个数字编写全局代码。

所以这是我的 2 位数代码:

var a = 23
var b = Math.floor(a/10); // 2
var c = a-b*10; // 3
var total = b+c; // 2+3
console.log(total); // 5

这是我的 3 位数代码:

var a = 456
var b = Math.floor(a/100); // 4
var c = a-b*100; // 56
var d = Math.floor(c/10); // 5
var e = c-d*10; // 6
var total = b+d+e; // 4+5+6
console.log(total); // 15

但我无法编写代码来处理每个数字。如何为每个数字编写全局代码?

最佳答案

在现代浏览器中,你可以像这样进行数组操作

var num = 4563;
var sum = ('' + num).split('').reduce(function (sum, val) {
return sum + +val
}, 0)

演示:Fiddle

首先创建一个数组 digits 然后使用 reduce 对数组中的值求和

关于javascript - 如何在 Javascript 中将数字拆分成数字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30025888/

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