給定一個數字串列const arr = [{ key1: 10 }, { key2: 5 }, { key3: 7 }, { key4: 17 }];和一個數字 k say const k = 17;,回傳串列中的任意兩個數字加起來是否為 k。例如,給定 [10, 15, 3, 7] 和 k = 17,我們應該回傳 True,因為 10 7 =17。
key,values在Map中使用寫了下面的代碼,但似乎無法得到解決方案,誰能建議下面需要更改哪些代碼,特別想解決使用Maps
const arr = [{ key1: 10 }, { key2: 5 }, { key3: 7 }, { key4: 17 }];
const k = 17;
let addInput = new Map(arr.flatMap((x) => Object.entries(x)));
addInput.forEach((v) => {
for (var i = 0; i < addInput.size; i ) {
if (v != addInput[i]) {
if (addInput[i] v == k) {
console.log(`${v} ${addInput[i]} = ${k} (true)`);
}
}
}
});
uj5u.com熱心網友回復:
您的代碼的方法不清楚:您應該使用Setto remove duplicate notMap并且您應該使用map運算子從物件中提取值,您也不能訪問具有數字索引(如陣列)的映射運算子。
const arr = [{ key1: 10 }, { key2: 5 }, { key3: 7 }, { key4: 17 }];
const k = 17;
// using set to remove duplicate
let valueSet = new Set(arr.flatMap((x) => Object.values(x)));
// using array to iterate easily, convert by destruturing
let valueArray = [...valueSet];
valueArray.forEach((v1, i1) => {
for (let i2 = i1 1 ; i2 < valueArray.length; i2 ) {
if ((v1 valueArray[i2]) === k) {
console.log(`${v1} ${valueArray[i2]} = ${k} (true)`);
}
}
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/369890.html
