我應該撰寫一個函式,它接受一個數字陣列并回傳一個字串。該函式應該使用過濾器、排序和減少來回傳一個只包含奇數的字串,以升序用逗號分隔。
我似乎無法讓我的 .reduce 方法實際回傳任何內容,而且我的 if 條件似乎無法正常作業......(例如,它在最后一個數字的輸出后添加一個逗號和空格,如“3 , 17, ")
這是我到目前為止所做的代碼......
const numSelectString = (numArr) => {
// use .filter to select only the odd numbers
numArr.filter((num) => num % 2 !== 0)
// use. sort to sort the numbers in ascending order
.sort((a,b) => a-b)
// use reduce to create the string and put the commas and spaces in
.reduce((acc, next, index) => {
if (index 1!==undefined) {
return acc = acc next ', ';;
} else {
return acc next;
}
},'')
}
const nums = [17, 34, 3, 12]
console.log(numSelectString(nums)) // should log "3, 17"
有沒有人有時間幫我整理一下我的reduce方法?我試圖傳入索引來確定reduce是否在最后一個元素上迭代以在最后一個元素之后不輸出“,”......但還沒有讓它作業......另外,我仍然不明白為什么我的輸出總是“未定義”!
謝謝你的幫助!
uj5u.com熱心網友回復:
您可以僅通過添加而不使用起始值來替換檢查。
const
numSelectString = numArr => numArr
.filter((num) => num % 2 !== 0)
.sort((a, b) => a - b)
.reduce(
(acc, next, index) => index
? acc ', ' next
: next,
''
);
console.log(numSelectString([17, 34, 3, 12]));
console.log(numSelectString([2, 4, 6]));
console.log(numSelectString([1, 2]));
uj5u.com熱心網友回復:
而不是使用index 1!==undefined,試試這個
const numSelectString = (numArr) => {
const numArrLength = numArr.length;
const arr = [...numArr];
arr
.filter((num) => num % 2 !== 0)
.sort((a,b) => a - b)
.reduce((acc, next, index) => {
if (index < numArrLength - 1) return acc = `${next}, `;
else return acc `${next}`;
}, "")
return arr;
}
不改變引數也被認為是一種很好的做法。
另一種方法
使用該.join()方法使它變得容易。
const numSelectString = (numArr) => {
const arr = [...numArr]
arr
.filter((num) => num % 2 !== 0)
.sort((a,b) => a-b)
.join(", ");
return arr;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/367591.html
標籤:javascript 数组 排序 筛选 降低
