```where, `type="text"` represents the input box type For text, `id="inp">
JavaScript is a programming language widely used in Web development. It can facilitate the development and interaction of front-end pages. Today we will learn how to input integers and sum them in JavaScript.
In JavaScript, you can create a text input box on a web page through the following code:
Among them,type="text"
indicates that the input box type is text,id="inputNum"
Indicates that the identifier of the input box is "inputNum", which is convenient for later calling in JavaScript.
Next, we need to create a summation function, which can be implemented through the following code:
function sum() { var input = document.getElementById("inputNum").value; // 获取输入框中的值 var nums = input.split(","); // 将输入的字符串以逗号为分隔符拆分成数字数组 var total = 0; for (var i = 0; i < nums.length; i++) { total += parseInt(nums[i]); // 将数组中的每个元素转换为整数并累加 } alert("总和为:" + total); // 弹出提示框显示结果 }
In the above code,document.getElementById("inputNum")
Indicates getting the element whose id is inputNum,.value
means getting the value entered in the element.input.split(",")
means splitting the input string into a numeric array using commas as delimiters.total = parseInt(nums[i])
means converting each element in the array to an integer and accumulating it. Finally, a prompt box pops up to display the calculation results through thealert
function.
Finally, we need to create a button in the web page. When the user clicks the button, the sum function written above is called. The following is the complete code:
In the above code,onclick="sum()"
means that the summation functionsum()
is called when the user clicks the button . Enter several numbers on the page, separated by commas, and click the "Sum" button to get their sum.
The JavaScript method for inputting integers and summing them is very simple and can be easily implemented through the above code. In actual web development, we can modify and optimize it as needed to achieve more complete functions.
The above is the detailed content of JAVAscript input integers and sum. For more information, please follow other related articles on the PHP Chinese website!