Javascript 创建一个 <ul> 并根据传递的数组填充它

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11128700/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 04:36:18  来源:igfitidea点击:

Create a <ul> and fill it based on a passed array

javascriptarrays

提问by gmeben

I've managed to generate a series of list-items based on one specified array within a matrix (i.e. an array within an array).

我设法根据矩阵中的一个指定数组(即数组中的数组)生成了一系列列表项。

I would like to be able to pass a variable (representing an array) to a function so that it can spit out an unordered list filled with list-items based on the array passed into it.

我希望能够将一个变量(代表一个数组)传递给一个函数,以便它可以根据传入的数组吐出一个填充有列表项的无序列表。

Problems:

问题:

  • The function only works with one array at a time
  • It also produces commas in the markup (presumably, because it's converting the array to a string)
  • 该函数一次只能处理一个数组
  • 它还在标记中生成逗号(大概是因为它将数组转换为字符串)

The solution needs to:

解决方案需要:

  • assume that the unordered list does not exist in the DOM
  • be able to accept different arrays passed into it (options[0], options[1], etc.)
  • generate the list-items without commas
  • 假设 DOM 中不存在无序列表
  • 能够接受传递到它的不同阵列(options[0]options[1]等)
  • 生成不带逗号的列表项

JavaScript:

JavaScript:

var options = [
        set0 = ['Option 1','Option 2'],
        set1 = ['First Option','Second Option','Third Option']
    ]

function makeUL(){
    var a = '<ul>',
        b = '</ul>',
        m = [];

    // Right now, this loop only works with one
    // explicitly specified array (options[0] aka 'set0')
    for (i = 0; i < options[0].length; i += 1){
        m[i] = '<li>' + options[0][i] + '</li>';
    }

    document.getElementById('foo').innerHTML = a + m + b;
}

// My goal is to be able to pass a variable
// here to utilize this function with different arrays
makeUL();

jsFiddle

js小提琴

回答by Ry-

First of all, don't create HTML elements by string concatenation. Use DOM manipulation. It's faster, cleaner, and less error-prone. This alone solves one of your problems. Then, just let it accept any array as an argument:

首先,不要通过字符串连接来创建 HTML 元素。使用 DOM 操作。它更快、更干净且不易出错。仅此一项就可以解决您的问题之一。然后,让它接受任何数组作为参数:

var options = [
        set0 = ['Option 1','Option 2'],
        set1 = ['First Option','Second Option','Third Option']
    ];

function makeUL(array) {
    // Create the list element:
    var list = document.createElement('ul');

    for (var i = 0; i < array.length; i++) {
        // Create the list item:
        var item = document.createElement('li');

        // Set its contents:
        item.appendChild(document.createTextNode(array[i]));

        // Add it to the list:
        list.appendChild(item);
    }

    // Finally, return the constructed list:
    return list;
}

// Add the contents of options[0] to #foo:
document.getElementById('foo').appendChild(makeUL(options[0]));

Here's a demo.You might also want to note that set0and set1are leaking into the global scope; if you meant to create a sort of associative array, you should use an object:

这是一个演示。您可能还想注意到,set0并且set1正在泄漏到全局范围内;如果你打算创建一种关联数组,你应该使用一个对象:

var options = {
    set0: ['Option 1', 'Option 2'],
    set1: ['First Option', 'Second Option', 'Third Option']
};

And access them like so:

并像这样访问它们:

makeUL(options.set0);

回答by Beamer

What are disadvantages of the following solution? Seems to be faster and shorter.

以下解决方案的缺点是什么?似乎更快更短。

var options = {
    set0: ['Option 1','Option 2'],
    set1: ['First Option','Second Option','Third Option']
};

var list = "<li>" + options.set0.join("</li><li>") + "</li>";
document.getElementById("list").innerHTML = list;

回答by Mihai Damian

You may also consider the following solution:

您还可以考虑以下解决方案:

let sum = options.set0.concat(options.set1);
const codeHTML = '<ol>' + sum.reduce((html, item) => {
    return html + "<li>" + item + "</li>";
        }, "") + '</ol>';
document.querySelector("#list").innerHTML = codeHTML;