Javascript Arrays And Closures
Earlier I posted a question about accessing array values stored in functions, passing array value using closure, and was told that this code would would do the job.
Solution 1:
How about
functionArrValues(arr) {
var values = {
'one': ['grapes','peaches','plums'],
'two': ['car','motorcycle','tree'],
'three': ['200','1000','350']
};
return values[arr];
}
(it does not handle the all
case as you do not describe what to return in this case..)
if with all
you want all values merged in a single array then
functionArrValues(arr) {
var match,
values = {
'one': ['grapes','peaches','plums'],
'two': ['car','motorcycle','tree'],
'three': ['200','1000','350']
};
if (arr!=='all'){
match = values[arr];
} else {
match = values['one'].concat( values['two'] ).concat( values['three'] );
}
returnmatch;
}
Solution 2:
Not really. Since you're not interested in the "else" case, you would be better off with this:
if( arr == "one" || arr == "all") return ['grapes','peaches','plums'];
And similar constructs.
That being said, if you do this then the so-called "all" button will only ever return the "one" array, because it will always match the first if
statement and return the array.
Post a Comment for "Javascript Arrays And Closures"