假设我们有两个这样的对象-
const obj1 = { positive: ['happy', 'excited', 'joyful'], negative: ['depressed', 'sad', 'unhappy'] }; const obj2 = { happy: 6, excited: 1, unhappy: 3 };
我们需要编写一个接受两个这样的对象的JavaScript函数。然后,该函数应同时使用这两个对象来计算正负得分,并返回如下对象:
const output = {positive: 7, negative: 3};
为此的代码将是-
const obj1 = { positive: ['happy', 'excited', 'joyful'], negative: ['depressed', 'sad', 'unhappy'] }; const obj2 = { happy: 6, excited: 1, unhappy: 3 }; const findPositiveNegative = (obj1 = {}, obj2 = {}) => { const result ={} for (let key of Object.keys(obj1)) { result[key] = obj1[key].reduce((acc, value) => { return acc + (obj2[value] || 0); }, 0) }; return result; }; console.log(findPositiveNegative(obj1, obj2));
输出结果
控制台中的输出将是-
{ positive: 7, negative: 3 }