输入一个数字并编写一个函数,在 JavaScript 中单击按钮后将数字上的位数相加


我们要求编写一个 JavaScript 程序,该程序为用户提供输入数字的输入。

并且在用户单击按钮时,我们应该显示数字的所有位数之和。

示例

代码如下 −

JavaScript 代码

function myFunc() {
   var num = document.getElementById('digits').value;
   var tot = 0;
   num.split('').forEach( function (x) {
      tot = tot + parseInt(x,10);
   });
document.getElementById('output').innerHTML = tot;
}

HTML 代码

<input id="digits" />
<button onClick="myFunc()">Submit</button>
<div id="output"></div>

输出

输出为 &miuns;:

单击“提交”按钮后 −

更新于: 2020 年 11 月 24 日

532 浏览量

开启您的 事业

完成课程后获得认证

入门
广告
© . All rights reserved.