构造一个函数objOfMatches
,它接受两个数组和一个回调。 objOfMatches
将建立一个对象并返回它。为了构建对象,objOfMatches
将使用回调测试第一个数组的每个元素,以查看输出是否匹配第二个数组的相应元素(按索引)。如果存在匹配项,则第一个数组中的元素将成为对象中的键,而第二个数组中的元素将成为对应的值。到目前为止,我知道了:
const objOfMatches = (arr1,arr2,call) => {
let result = {};
for(let i = 0; i < arr1.length; i++){
//Don't know how to check each element using the callback
}
return result
}
const arr1 = ['hi', 'howdy', 'bye', 'later', 'hello'];
const arr2 = ['HI', 'Howdy', 'BYE', 'later', 'HELLO'];
function uppercaser(str) { return str.toUpperCase(); }
console.log(objOfMatches(arr1, arr2, uppercaser));
// should log: { hi: 'HI', bye: 'BYE', hello: 'HELLO' }
尝试一下:
const objOfMatches = (arr1,arr2,call) => {
let result = {};
for(let i = 0; i < arr1.length; i++){
let upper = call(arr1[i]);
if(arr2[i] && upper == arr2[i])
result[arr1[i]] = arr2[i];
}
return result
}
const arr1 = ['hi', 'howdy', 'bye', 'later', 'hello'];
const arr2 = ['HI', 'Howdy', 'BYE', 'later', 'HELLO'];
function uppercaser(str) { return str.toUpperCase(); }
console.log(objOfMatches(arr1, arr2, uppercaser));
const objOfMatches = (arr1,arr2,call) => {
let result = {};
for(let i = 0; i < arr1.length; i++){
if(call(arr1[i]) === arr2[i]) {
result[arr1[i]] = arr2[i]
}
}
return result;
}
const arr1 = ['hi', 'howdy', 'bye', 'later', 'hello'];
const arr2 = ['HI', 'Howdy', 'BYE', 'later', 'HELLO'];
function uppercaser(str) { return str.toUpperCase(); }
console.log(objOfMatches(arr1, arr2, uppercaser));
// should log: { hi: 'HI', bye: 'BYE', hello: 'HELLO' }
这里是一个功能编程解决方案:
const objOfMatches = (arr1, arr2, call) =>
Object.fromEntries(arr1
.map((v,i) => [v, arr2[i]])
.filter(([a,b]) => call(a) === b)
);
const arr1 = ['hi', 'howdy', 'bye', 'later', 'hello'];
const arr2 = ['HI', 'Howdy', 'BYE', 'later', 'HELLO'];
const uppercaser = str => str.toUpperCase();
console.log(objOfMatches(arr1, arr2, uppercaser));