如何制作更轻量级的JavaScript?

时间:2013-10-03 10:48:39

标签: javascript

我有以下javascript。

有没有让这更简单。看起来很重?

它基本上取12个输入的值并根据这些值更改数组

   function updatechart (){
    var inputnoinsulation1 = document.getElementById("noinsulation1").value
    var inputnoinsulation2 = document.getElementById("noinsulation2").value
    var inputnoinsulation3 = document.getElementById("noinsulation3").value
    var inputnoinsulation4 = document.getElementById("noinsulation4").value
    var inputnoinsulation5 = document.getElementById("noinsulation5").value
    var inputnoinsulation6 = document.getElementById("noinsulation6").value
    var inputnoinsulation7 = document.getElementById("noinsulation7").value
    var inputnoinsulation8 = document.getElementById("noinsulation8").value
    var inputnoinsulation9 = document.getElementById("noinsulation9").value
    var inputnoinsulation10 = document.getElementById("noinsulation10").value
    var inputnoinsulation11 = document.getElementById("noinsulation11").value
    var inputnoinsulation12 = document.getElementById("noinsulation12").value

    chart1data[0].NoInsulation = (parseInt(inputnoinsulation1));
    chart1data[1].NoInsulation = (parseInt(inputnoinsulation2));
    chart1data[2].NoInsulation = (parseInt(inputnoinsulation3));
    chart1data[3].NoInsulation = (parseInt(inputnoinsulation4));
    chart1data[4].NoInsulation = (parseInt(inputnoinsulation5));
    chart1data[5].NoInsulation = (parseInt(inputnoinsulation6));
    chart1data[6].NoInsulation = (parseInt(inputnoinsulation7));
    chart1data[7].NoInsulation = (parseInt(inputnoinsulation8));
    chart1data[8].NoInsulation = (parseInt(inputnoinsulation9));
    chart1data[9].NoInsulation = (parseInt(inputnoinsulation10));
    chart1data[10].NoInsulation = (parseInt(inputnoinsulation11));
    chart1data[11].NoInsulation = (parseInt(inputnoinsulation12));

3 个答案:

答案 0 :(得分:5)

for (var i = 0; i < 12; i++)
     chart1data[i].NoInsulation = parseInt(document.getElementById("noinsulation" + (i + 1)).value);

应该工作。

答案 1 :(得分:0)

var i = 0, l = 12;

for (;i<l;++i) {
    var val = window.parseInt(document.getElementById("noinsulation"+ (i+1)).value, 10);
    chart1data[i].NoInsulation = val;
}

答案 2 :(得分:0)

试试这个:

var index = 0;
while (index < 12) chart1data[index++].NoInsulation =
    parseInt(document.getElementById("noinsulation" + index).value);

此外,指定parseInt的第二个参数(即基数)始终是一个好习惯。在这种情况下它不会有任何区别,但你应该养成这样做的习惯:

var index = 0;
while (index < 12) chart1data[index++].NoInsulation =
    parseInt(document.getElementById("noinsulation" + index).value, 10);

希望这有帮助。