您正在修改循环内的变量prevalue
(由循环条件共享),您每次都检查长度作为循环条件。每次它在循环中添加一些东西,所以它会继续运行。它曾经是一个array
并且在将字符串添加到它之后,它会强制转换为string
from array
,然后在病房中检查字符串的长度,然后您继续附加到它,它会一直持续下去。
尝试:
$(function(){
$('#sum').keyup(function(){
var prevalue=$('#sum').val().split(","), sum = 0;
for (var i=0;i<prevalue.length;i++){
sum += parseInt(prevalue[i], 10) || 0; //<--- Use a parseInt to cast it or use parseFloat
}
$('h1').html(sum); //<-- move it to out of the loop
});
});
小提琴
你的代码:
$(function () {
$('#sum').keyup(function () {
var prevalue = $('#sum').val().split(","); //<-- Iteration 1 prevalue is an array
for (i = 0; i < prevalue.length; i++) { //iteration1 : it looks for array.length
prevalue += prevalue[i]; //Changes the variable shared by the loop to string from array and string also has its length. And next time onwards it adds to itself a char from the string and length increases and loop goes infinitely.
$('h1').html(prevalue); //<-- Doesn't make any sense here.
}
});
});