Reputation: 2063
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 solution needs to:
options[0]
, options[1]
, etc.)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();
Upvotes: 61
Views: 141366
Reputation: 1
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;
Upvotes: -2
Reputation: 828
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;
Upvotes: 9
Reputation: 224962
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:
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 set0
and set1
are leaking into the global scope; if you meant to create a sort of associative array, you should use an object:
var options = {
set0: ['Option 1', 'Option 2'],
set1: ['First Option', 'Second Option', 'Third Option']
};
And access them like so:
makeUL(options.set0);
Upvotes: 103