javascript - is `.map` not for looping? -
i've answered question here before how number of response of json? , suggested them use map function instead of using for loop commented .map not looping , use foreach instead.
are there downsides using map on for loop?
i researched , found site stating map > foreach .
map used transform each element in array representation, , returns results in new sequence. however, since function invoked each item, possible make arbitrary calls , return nothing, making act foreach, although strictly speaking not same.
proper use of map (transforming array of values representation):
var source = ["hello", "world"]; var result = source.map(function(value) { return value.touppercase(); }); console.log(result); // should emit ["hello, "world"] accidentally using .map iterate (a semantic error):
var source = ["hello", "world"]; // emits: // "hello" // "world" source.map(function(value) { console.log(value); }); the second example technically valid, it'll compile , it'll run, not intended use of map.
"who cares, if want?" might next question. first of all, map ignores items @ index have assigned value. also, because map has expectation return result, doing things, allocating more memory , processing time (although minute), simple process. more importantly, may confuse or other developers maintaining code.
Comments
Post a Comment