javascript - create variable from string given in array
问题描述
Is there any way to create variable from String inside the array with the name of the String?
something like this:
const array = ["type","name","hours","photos","place","price"];
array.forEach(item =>{
let item = document.crea.....
//but it should work like let array[index] = docu.......
})
The reason for this is that I wanted to make this code look a bit nicer and its obvious, that there are quite a lot things repeating.
const type = document.createElement("td");
const name = document.createElement("td");
const hours = document.createElement("td");
const photos = document.createElement("td");
const place = document.createElement("td");
const price = document.createElement("td");
type.innerHTML = element.type;
name.innerHTML = element.name;
hours.innerHTML = element.hours;
photos.innerHTML = element.photos;
place.innerHTML = element.place;
price.innerHTML = element.price;
tr.appendChild(type);
tr.appendChild(name);
tr.appendChild(hours);
tr.appendChild(photos);
tr.appendChild(place);
tr.appendChild(price);
解决方案
我知道这并不能直接回答您关于变量名的问题,但这应该是您获得结果所需的代码。
array.forEach(item => {
const elem = tr.appendChild(document.createElement("td"));
elem.innerHTML = item;
})
您实际上并不需要使用数组来生成变量名称,因为 forEach 会分别处理数组中的每个项目。
推荐阅读
- kotlin - 在不使用双反斜杠文件分隔符的情况下列出 Windows 操作系统文件夹的文件
- javascript - 将 prevstate 参数添加到 this.setState 会导致 typeError
- php - Mysqli 选择具有相同 id 和 sum 的多行然后在 PHP 中返回
- spring - 无法通过容器内的 HandlerResolver 动态设置 Basic Auth 标头
- php - 限制特定用户角色 laravel 的 URL
- c++ - C++分数混合比较运算符错误
- pic - PIC的EEPROM可以写程序吗?
- android - 从“RecyclerView”获取图像资源
- python - python中方便的循环减法方法?
- laravel - 未找到 Xampp 对象!错误,无法发布新帖子