lodash中_.forEach和_.forOwn之间的区别

Nov*_*tor 43 foreach lodash

迭代对象时这两种方法有什么区别?

Tha*_* K. 62

不同之处在于,如果您正在迭代的集合是具有length属性的对象,那么_.forEach()将迭代它就像它是一个数组一样,而_.forOwn()将像对象一样迭代它.

假设你有这个对象:

a = {
  x: 100, 
  y: 200, 
  length: 2
}
Run Code Online (Sandbox Code Playgroud)

如果你迭代它:

_.forEach(a, function(val, key) {
  console.log('a[' + key + '] = ' + val); 
});
Run Code Online (Sandbox Code Playgroud)

你会得到输出:

a[0] = undefined
a[1] = undefined 
Run Code Online (Sandbox Code Playgroud)

而迭代它_.forOwn()会让你更合理:

a[x] = 100
a[y] = 200
a[length] = 2
Run Code Online (Sandbox Code Playgroud)