任務是:
給定一個數字陣列,回傳一個新的長度為 number 的陣列,其中包含原始陣列中的最后一個偶數(以相同的順序)。
Codewars 編譯器顯示“執行超時(12000 毫秒)”錯誤,但代碼按預期作業。請幫助優化我的代碼,因為我自己無法弄清楚
我的代碼:
function evenNumbers(array, number) {
for (let i=0; i < array.length; i ) {
if (array[i] % 2 != 0) {
array.splice(i, 1);
i -= 1;
}
}
array.splice(0, array.length - number)
return array;
}
uj5u.com熱心網友回復:
您正在遍歷整個陣列,但您只需要遍歷number元素。例如,給定 anumber為 5,您只需要迭代直到找到滿足條件的 5 個值 - 如果不需要,您不想迭代整個 10,000 長度的陣列。(Codewars 測驗通常具有如此龐大的物件結構。)
它還說回傳一個新陣列,而不是修改現有陣列。
const evenNumbers = (array, number) => {
const newArr = [];
for (let i = array.length - 1; i >= 0 && newArr.length <= number; i--) {
if (array[i] % 2 === 0) newArr.unshift(array[i]);
}
return newArr;
};
console.log(evenNumbers(
[1, 2, 3, 4, 5, 6, 7, 8],
3
));
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/347923.html
標籤:javascript 循环 优化
下一篇:這個回圈是如何作業的?我無法理解
