35
迭代對象時,這兩種方法之間有什麼區別?lodash中的_.forEach和_.forOwn之間的區別
迭代對象時,這兩種方法之間有什麼區別?lodash中的_.forEach和_.forOwn之間的區別
不同之處在於,如果在你所遍歷collection是具有length
屬性的對象,那麼_.forEach()
會遍歷它,就好像它是一個數組,而_.forOwn()
會遍歷它像一個對象。
假設你有對象:
a = {
x: 100,
y: 200,
length: 2
}
如果您遍歷它:
_.forEach(a, function(val, key) {
console.log('a[' + key + '] = ' + val);
});
你會得到輸出:
a[0] = undefined
a[1] = undefined
而遍歷它與_.forOwn()
你會得到更合理的:
a[x] = 100
a[y] = 200
a[length] = 2