![](/img/trans.png)
[英]Why does react render differently in these two cases when using redux?
[英]Why does underscore.reduce acts differently in these two cases?
我試圖展平其中有兩個對象的對象,所以我做了以下工作:
var underscore = require('underscore');
var obj = { a: {x:1}, b: {y:2}};
underscore.reduce(obj, underscore.extend, {});
出乎意料的是,我得到的輸出是:
{
'0': 'b',
x: 1,
a: { x: 1 },
b: { y: 2 },
y: 2
}
因此,然后我嘗試將extend
包裝在一個函數中:
underscore.reduce(obj, function(memo, o) {
return underscore.extend(memo, o);
}, {});
並得到了預期的結果:
{ x: 1, y: 2 }
為什么有什么區別? reduce
期望的作為第二個參數的函數,該函數將獲取兩個參數並返回一個參數,並且在兩種情況下均將其獲取。 那我想念什么呢?
reduce
期望作為第二個參數的函數,該函數將獲取兩個參數並返回一個參數...
沒有根據文檔 。 下划線傳遞給迭代器四個而不是兩個參數:
傳遞給迭代器四個參數:
memo
,然后是迭代的value
和index
(或key
),最后是對整個list
的引用。
因此,您最終會這樣調用extend
(在第一遍):
underscore.extend({}, {x: 1}, 'a', obj)
然后第二遍
underscore.extend({/*...stuff...*/}, {y: 2}, 'b', obj)
對象具有'0': 'b'
屬性的原因是字符串延伸到包含'<index>': '<char>'
類'<index>': '<char>'
屬性的對象中。 這是因為_.extend
在每個參數(第一個參數除外)上運行for...in...
循環,並且通過此操作找到的鍵是字符索引(從0
到str.length - 1
)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.