component / each

Object / array / array-ish / string iteration utility
14 stars 13 forks source link

Question on the order of callback parameters for iteration over object. #9

Open mnmly opened 11 years ago

mnmly commented 11 years ago

Hi, I'm a bit wondering why the order of the parameters are kinda reversed on object iteration. If there's any reason why the order is in this way, it would be helpful if you can share your thoughts in order for me and potentially others to avoid relevant mistakes and such.

Currently when you iterate over object, you will get key, (or property name) as the first argument:

var conf = {
  fast: 1,
  normal: 0.5,
  slow: 0.3
};
each(conf, function(key, val){
  console.log(val, key); // => 1, "fast"... 
})

But if we consider key to be more like index, the following order is a bit more consistent compared to other types, where val is always passed as first argument.

var conf = {
  fast: 1,
  normal: 0.5,
  slow: 0.3
};
each(conf, function(val, key){
  console.log(val, key);  // => 1, "fast"... 
})

each("something", function(val, index){
  console.log(val, index)  // => "s", 0... 
})

each(['a', 'b', 'c'], function(val, index){
  console.log(val, index); // => "a", 0…
})

underscore.js and lodash.js are passing val in the first parameter:

var _ = require('underscore') // require('lodash');
var conf = {
  fast: 1,
  normal: 0.5,
  slow: 0.3
};
_.each(conf, function(val, key){
  console.log(val, key); // => 1, "fast"... 
})
TooTallNate commented 10 years ago

Very good points @mnmly. +1 for swapping the object mode arguments, and tagging a v1.

rauchg commented 10 years ago

+100