javascript - 用 getElementById 填充数组

标签 javascript arrays getelementbyid

我正在尝试使用 getElementById 将我在 HTML 文件中的数字填充到一个数组中。

对于 HTML,我尝试使用:

<div id="E1_INV_Funds0">1</div>
<div id="E1_INV_Funds1">2</div>
<div id="E1_INV_Funds2">3</div>
<div id="E1_INV_Funds3">4</div>
<div id="E1_INV_Funds4">5</div>
<div id="E1_INV_Funds5">6</div>
<div id="E1_INV_Funds6">7</div>
<div id="E1_INV_Funds7">8</div>

然后使用以下 Javascript:

<script type="text/javascript">

 var graphData = [];

 function fillData(){
   for( var i = 0; i < 8; i++ ) {
    graphData[i] = parseInt(document.getElementById("E1_INV_Funds" + i).value);
    return graphData;
   }
}

console.log(graphData);

</script>

这不会返回任何内容。

是什么导致了这种行为?

最佳答案

在您的代码中,return 在任何迭代完成之前立即终止函数。另一个问题是 .value 仅适用于类似输入的元素 - 要从 div 中提取文本,请访问其 textContent 属性。

如何使用 Array.from 及其内置的 mapping 函数,它不需要任何外部突变?

const graphData = Array.from(
  { length: 8 },
  (_, i) => Number(document.getElementById('E1_INV_Funds' + i).textContent)
);
console.log(graphData);
<div id="E1_INV_Funds0">1</div>
<div id="E1_INV_Funds1">2</div>
<div id="E1_INV_Funds2">3</div>
<div id="E1_INV_Funds3">4</div>
<div id="E1_INV_Funds4">5</div>
<div id="E1_INV_Funds5">6</div>
<div id="E1_INV_Funds6">7</div>
<div id="E1_INV_Funds7">8</div>

Array.from({ length }, mapFn) 只是创建长度为 length 的新数组的功能方法。将具有 length 属性的对象传递给 Array.from 创建一个 undefined 数组,第二个参数与 相同Array.prototype.map,在返回之前应用于结果数组。对于 .map,第一个参数是数组值(此处无用),第二个参数是被迭代项的索引,这正是我们想要的。 _ 只是一个指示器,表明那里的参数不会被使用。

参见 MDN

关于javascript - 用 getElementById 填充数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50574678/

相关文章:

javascript - 通过jquery或javascript将信息从一个网页传递到另一个页面?

javascript - 如何使用double for 语句创建一个循环来排序Array 来处理有月和日的Array?

JavaScript 对象不改变图像

Javascript 函数并不执行所有指令

javascript - 如果您知道对象数组中的另一个值,则在对象数组中查找该元素

javascript - 动态在表中添加行 - Bootstrap 和 JS

java - 字母数字拨号盘搜索 - Java/Android

c - 在C函数中传递二维数组

javascript - 通过 'class' 而不是 'id' 引用元素

Javascript:如何强制 POST 请求将用户视为未经过身份验证