我正在尝试使用 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
及其内置的 map
ping 函数,它不需要任何外部突变?
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/