【发布时间】:2019-03-20 17:37:47
【问题描述】:
我有一个关于跟随的问题,我必须从 list1 创建 list2,所以我应用了效果很好的解决方案 1。但是,我必须将其作为单元测试的单独功能。更改后,我无法使其像解决方案 2 那样。如果我打印返回值,它会显示数组的 3 个元素未定义。有人对这个问题有什么建议吗?我已经很努力了,但我仍然无法解决它。
var list1 = [
{ firstName: 'Sofia', lastName: 'I.', country: 'Argentina', continent: 'Americas', age: 35, language: 'Java' },
{ firstName: 'Lukas', lastName: 'X.', country: 'Croatia', continent: 'Europe', age: 35, language: 'Python' },
{ firstName: 'Madison', lastName: 'U.', country: 'United States', continent: 'Americas', age: 32, language: 'Ruby' }
];
var list2 = [
{ firstName: 'Sofia', lastName: 'I.', country: 'Argentina', continent: 'Americas', age: 35, language: 'Java',
greeting: 'Hi Sofia, what do you like the most about Java?'
},
{ firstName: 'Lukas', lastName: 'X.', country: 'Croatia', continent: 'Europe', age: 35, language: 'Python',
greeting: 'Hi Lukas, what do you like the most about Python?'
},
{ firstName: 'Madison', lastName: 'U.', country: 'United States', continent: 'Americas', age: 32, language: 'Ruby',
greeting: 'Hi Madison, what do you like the most about Ruby?'
}
];
解决方案 1
let greetings1 = list1.map(person => {
return Object.assign(
{ firstName: person.firstName },
{ lastName: person.lastName },
{ country: person.country },
{ continent: person.continent },
{ age: person.age },
{ language: person.language },
{
greeting: `Hi ${person.firstName}, what do you like the most about ${
person.language
}?`
}
);
});
解决方案 2
function greetDevelopers(list1) {
const greetings = list1.map(person => {
Object.assign(
{ firstName: person.firstName },
{ lastName: person.lastName },
{ country: person.country },
{ continent: person.continent },
{ age: person.age },
{ language: person.language },
{
greeting: `Hi ${person.firstName}, what do you like the most about ${
person.language
}?`
}
);
});
return greetings;
}
【问题讨论】:
-
解决方案 2 不返回
undefined中的map以外的其他值。只需添加return。顺便说一句,真正的问题是什么? -
你为什么用
Object.assign而不是写:{firstName: person.firstName, lastName: person.lastName, country: person.country, continent: person.continent /*, ... */ }?您对此有何期待? -
如问题所述,我期望 list2。我太傻了,忘记退货了。无论如何,非常感谢。
标签: javascript dictionary functional-programming