首页 > 解决方案 > 如何提取保存在 for 中的值?...这是我的代码。但它不起作用

问题描述

var table = document.getElementById("table"),
  sumVal = 0;

var aux = '';

function prueba() {
  for (var i = 1; i < table.rows.length; i++) {
    var sumVal = parseInt(table.rows[i].cells[1].innerHTML);
    aux = sumVal;
    console.log(sumVal);

  }
}

标签: javascript

解决方案


问题是循环的每次迭代,您都在覆盖aux变量的值。您需要更改aux为一个数组,以便您可以添加到它。这是一个 Javascript 数组教程,可能可以帮助您理解。

var aux = [];//the array 

function prueba(){
  for(var i = 1; i < table.rows.length; i++){   
    var sumVal = parseInt(table.rows[i].cells[1].innerHTML);
    aux.push(sumVal);//add the value to the end of the array
  }
}
prueba();
console.log(aux);//console.log the contents of the array

推荐阅读