簡體   English   中英

用於返回數組的函數返回undefined。 函數內的Console.log(數組)返回數組

[英]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(數組)打印出預期的數組,但是當函數返回時數組是未定義的?

您不必返回旋轉陣列(每個遞歸調用),你需要另一個returnrotLeft(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) => {
  //console.log(array, n); // <-- this prints out expected array
  if (!n) return array; // <-- but this returns undefined! :(
  array.push(array.shift());
  return rotLeft(array, n - 1);
};

用法: rotLeft([1,2,3,4],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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM