在else子句中,带注释的行给出了所需的结果,但是下面的一行导致{'1':[1.3],'2':[2.1]}变为{'1':[1.3 ],'2':2}。我不明白为什么会这样。
const groupBy = (array, callback) => {
let obj = {}
for (let i = 0; i < array.length; i++) {
let currKey = callback(array[i])
let newVal = array[i]
let currVal = obj[currKey]
if (!currVal) {
obj[currKey] = [newVal]
} else {
// obj[currKey].push(newVal)
obj[currKey] = currVal.push(newVal)
}
}
return obj
}
// Uncomment these to check your work!
var decimals = [1.3, 2.1, 2.4]
var floored = function(num) { return Math.floor(num) }
groupBy(decimals, floored); // expect { 1: [1.3], 2: [2.1, 2.4] }
答案 0 :(得分:3)
Array.prototype.push
不返回新数组,而是返回数组的长度。
const groupBy = (array, callback) => {
// let arrayValues = [] // this isn't used anywhere
let obj = {}
for (let i = 0; i < array.length; i++) {
let currKey = callback(array[i])
let newVal = array[i]
let currVal = obj[currKey]
if (!currVal) {
obj[currKey] = [newVal]
} else {
obj[currKey].push(newVal) // this should work instead
//obj[currKey] = currVal.push(newVal)
}
}
return obj
}
由于数组是引用类型,因此您只需要将新项推入数组obj[currKey].push(newValue)
,而无需再次设置obj[currKey]
。您正在将一个新值推送到它存在于内存中的数组中,因此无需将其重新分配给任何值。您可以看到lodash here的工作方式(尽管您必须解开一些辅助函数)。
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push