首页 > 解决方案 > 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);

标签: javascripthtml

解决方案


我知道这并不能直接回答您关于变量名的问题,但这应该是您获得结果所需的代码。

array.forEach(item => {
    const elem = tr.appendChild(document.createElement("td"));
    elem.innerHTML = item;
})

您实际上并不需要使用数组来生成变量名称,因为 forEach 会分别处理数组中的每个项目。


推荐阅读