JavaScript 求和(字符串转换成数组、for循环求和)

在这里插入图片描述

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>数组求和与字符串求和</title>
		<style type="text/css">
			#case {
				width: 40%;
				height: 100px;
				margin: 50px auto;
			}
			input {
				width: 60%;
				height: 30px
			}
			p:last-child {
				background: #00FFFF;
				width: 50%;
				height: 50px;
				text-align: center;
				line-height: 50px;
				margin: 20px auto;
				cursor: pointer;
			}
		</style>
		<script type="text/javascript">
			window.onload = function() {
				var oInput = document.getElementsByTagName("input")[0];
				var oBtn = document.getElementsByTagName("p")[0];
				//当从表单中输入时,将不属于数字或者","的全部转换为空
				oInput.onkeyup=function(){
					this.value=this.value.replace(/[^(\d)|(,)]/,"")
				}
				oBtn.onclick = function() {
					var arr = oInput.value.split(","); //转换成数组
					var sum = 0;
					for (var item, i = 0; item = arr[i++];) {
						sum += parseInt(item); //数组求和(转换成整数)
					}
					alert(sum)
				}


			}
		</script>
	</head>
	<body>
		<div id="case">
			<form>
				<input type="text" value="1,2,3,4" id="demo" />(以逗号隔开)
			</form>
			<p>点击求和</p>
		</div>

	</body>
</html>

posted @ 2022-04-02 09:48  coderwcb  阅读(301)  评论(0)    收藏  举报