使用 JavaScript 将数字拆分为单个数字
在本文中,我们将使用 元素从用户那里获取一些输入,任务是在 JavaScript 的帮助下将给定的数字拆分为单个数字。下面讨论两种方法:
方法1:首先从输入元素中取出字符串格式的元素(无需将其转换为数字)并声明一个空数组(var res)。在字符串的长度上循环访问字符串的每个字符,并使用push() 方法将字符推送到数组(res)中。
- 示例:此示例实现了上述方法。
html
Split a number into individual
digits using JavaScript
GeeksforGeeks
Type the number and click on the button
to perform the operation.
Type here:
html
Split a number into individual digits
GeeksforGeeks
Type the number and click on the
button to perform the operation.
Type here:
- 输出:
方法2:首先以字符串格式从输入元素中获取元素(无需将其转换为数字)并声明一个空数组(var res)。使用(”) 上的split() 方法拆分字符串,并将拆分后的结果存储在数组 (str) 中。
- 示例:此示例实现了上述方法。
html
Split a number into individual digits
GeeksforGeeks
Type the number and click on the
button to perform the operation.
Type here:
- 输出: