我有几个文本值数组,我想使用其中一个来根据用户对另一个数据列表中值的选择来填充HTML数据列表。我不知道如何编码。
这是我的代码,但它不完整。看到????我可能需要一些额外的代码。将地图数组保留在HTML中还是将它们放在一个或多个文件(js或文本)中是最佳做法。如果它们应该在文件中,我不确定如何引用它们。
如果我硬编码使用map1或map2而不是mapArray,这是有效的。
<script>
var str=''; // variable to store the options
var mapName = map; //will be text "Map 1" or "Map 2" up to "Map 30"
var map1 = new Array("Caitlin", "Roadrunner", "More Values");
var map2 = new Array("Ceedee #1, Ceedee#2"); // up to 30 values
var mapArray[] = ????? //I want to copy the array for Map 1 or Map 2..
for (var i=0; i < mapArray.length;++i) {
str += '<option value="'+mapArray[i]+'" />'; // Storing options in
// variable
}
var my_list=document.getElementById("theList");
my_list.innerHTML = str;
</script>
听起来像是用于spread operator ...
var map1 = new Array("Caitlin", "Roadrunner", "More Values");
var map2 = new Array("Ceedee #1, Ceedee#2");
var mapArray = [...map1, ...map2];
// map1 is now ["Caitlin", "Roadrunner", "More Values", "Ceedee #1, Ceedee#2"]
您可以使用push数组函数在数组末尾存储新元素。
因此,如果您想创建数组的数组,可以执行以下操作:
var mapArray = new Array();
var map1 = new Array("Caitlin", "Roadrunner", "More Values");
mapArray.push(map1);
var map2 = new Array("Ceedee #1, Ceedee#2");
mapArray.push(map2);
这将导致值mapArray
等于[ map1, map2 ]
。
您需要修改for
循环,因为这是一个2D数组。
所以它可能看起来像:
// choice variable is the chosen input from user
for (var i=0; i < mapArray[choice].length; ++i) {
str += '<option value="'+mapArray[choice][i]+'" />';
}
至于你的其他问题,他们大多是基于意见的。我建议您使用所需的功能,然后从那里进行扩展,看看是否可以使代码更清晰。
无需复制数组,只需将所有可用选项存储在对象中,然后通过索引访问所需的数组。
此外,您可以填充<select/>
元素而不构建字符串。通过使用Option()
,您的代码将更不容易出现未转义的字符问题。
const selectedMap = 'map1';
const maps = {
'map1': ["Caitlin", "Roadrunner", "More Values"],
'map2': ["Ceedee #1, Ceedee#2"]
};
let theList = document.getElementById("theList");
theList.options = []; // Empty out all previous options in the <select/> (if any)
maps[selectedMap].forEach((val, index) => {
theList[index] = new Option(val, val);
});
<select id='theList'></select>