<!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>
1200字范文,内容丰富有趣,写作的好帮手!