I have an array that contains another array as well as strings:
var text;
var languageSet = ["Language4", "Language5"];
var languages = [
["Language1", "Language2", "Language3"],
languageSet,
"Language6"
];
(function selector() {
for (i = 0; i < languages.length; i++) {
for (j = 0; j < languages[i].length; j++) {
text += "<option value='" + languages[i][j] + "'>" + languages[i][j] + "</options>";
}
}
document.getElementById("languageOptions").innerHTML = text;
})();
HTML:
<select id="languageOptions">
</select>
But everytime I run this, the output for "Language 6" ends up being as such:
L
a
n
g
u
a
g
e
6
How do I output that as an entire string? I don't know why my code doesn't work for strings and arrays inside arrays.
2 Answers 2
You should do a type check to see if your item is an array and then loop the array. I used Array.isArray here to do that type check. The code example is working for you to test.
The Array.isArray() method returns true if an object is an array, false if it is not.
var text;
var languageSet = ["Language4", "Language5"];
var languages = [
["Language1", "Language2", "Language3"],
languageSet,
"Language6"
];
(function selector() {
for (i = 0; i < languages.length; i++) {
if (Array.isArray(languages[i])) {
for (j = 0; j < languages[i].length; j++) {
text += "<option value='" + languages[i][j] + "'>" + languages[i][j] + "</options>";
}
} else {
text += "<option value='" + languages[i] + "'>" + languages[i] + "</options>";
}
}
document.getElementById("languageOptions").innerHTML = text;
})();
<select id="languageOptions">
</select>
Comments
Use Array.isArray() function to check the type inside the loop.
for (i = 0; i < languages.length; i++) {
if(Array.isArray(languages[i])) {
for (j = 0; j < languages[i].length; j++)
text += "<option value='" + languages[i][j] + "'>" + languages[i][j] + "</options>";
} else {
text += "<option value='" + languages[i] + "'>" + languages[i] + "</options>";
}
}
document.getElementById("languageOptions").innerHTML = text;
2 Comments
var str = 'hello'; is considered as array of characters plus String prototype methods. 0->h, 1->e 2->l 3->l 4->o ...I feel more you work and experience on this, you will get more clarity.
.lengthand indexed access). Just wrap your string in an array and it'll work.an array that contains another array as well as strings- then you will have to check if it's a string or an array in your code. If you can guarantee the data is formatted sensibly (array of arrays of strings, eg) then you don't have to check.