Maybe you don't need so many arrays? Lets use an object instead.
var isps = {
yahoo: ["@yahoo.com", "@rocketmail.com", "@ymail.com"],
gmail: ["@gmail.com"]
};
for(isp in isps) {
var providers = isps[isp];
document.write(isp + " has " + providers.length + " provider(s):<br/>");
providers.forEach(function(domain) {
document.write(domain + "<br/>");
});
};
This works because instead of looping through an array and trying to access different variables with the same name, you can instead simply loop through the keys of an object (which are the same as that first array) and use it to access the values of that object (which are the same as in the other variables you had before).
Note that I've changed your alert
s to things that will be more informative in running the code snippet. Of course, once you've got access to these values isp
, providers
and domain
, you can do whatever you like with them - you don't need to document.write
them.
There are a few benefits to this method. For instance, as we're only human, what if this happened:
var isp = ["yahoo"];
var yahooo = ["@yahoo.com"];
There's a dependency on the values in isp
and the variable names being exactly the same. A simple error like above ("yahooo" instead of "yahoo") would prevent the code from working, and a one letter bug like that could be quite difficult to find if you don't know what you're looking for.
If you're to come back and add or modify these values often, this could become a concern. With the object pattern, it's cleaner and more self-contained.
One potential concern with this solution, however, is if the order in which these providers are looped through is important (i.e. if you always need "yahoo" to output before "gmail"). Currently JavaScript states the following in regards to objects: "It is an unordered collection of properties". This could be subject to change in ES6 (we're currently on ES5). Read more about this particular issue here:
Does JavaScript Guarantee Object Property Order?