[英]Function that is intended to return an array is returning undefined. Console.log(array) within function returns the array
我正在嘗試編寫一個函數,該函數接受一個數組並返回一個新數組,所有元素都將n個索引向左移動。 例如:
rotLeft([1,2,3,4],2)
// should return [3,4,1,2]
我編寫了一個遞歸函數,它刪除了索引0處的值,並使用.shift()和.push()將其賦值給最后一個索引。
const rotLeft = (array, n) => {
console.log(array, n); // <-- this prints out expected array
if (!n) return array; // <-- but this returns undefined! :(
array.push(array.shift());
rotLeft(array, n - 1);
};
console.log(rotLeft([1, 2, 3, 4, 5, 6, 7], 9));
為什么每個console.log(數組)打印出預期的數組,但是當函數返回時數組是未定義的?
您不必返回旋轉陣列(每個遞歸調用),你需要另一個return
為rotLeft(array, n - 1)
const rotLeft = (array, n) => { // console.log(array, n); if (!n) return array; array.push(array.shift()); return rotLeft(array, n - 1); // <-- return the rotated array (recursively) }; console.log(...rotLeft([1, 2, 3, 4, 5, 6, 7], 2));
更短(使用concat
和三元運算符):
const rotLeft = (array, n) => { return n ? rotLeft(array.concat([array.shift()]), n - 1) : array; }; console.log(...rotLeft([1, 2, 3, 4, 5, 6, 7], 2));
您需要return
遞歸調用。
const rotLeft = (array, n) => { if (!n) return array; array.push(array.shift()); return rotLeft(array, n - 1); }; console.log(rotLeft([1, 2, 3, 4, 5, 6, 7], 9));
或者您可以使用Array.prototype.slice()來存檔它
const arr = [1,2,3,4] const rotLeft = (arr, n) => arr.slice(n).concat(arr.slice(0,n)) const tmp1 = rotLeft(arr, 2) const tmp2 = rotLeft(arr, 3) console.log("tmp1", tmp1) console.log("tmp2", tmp2)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.