簡體   English   中英

多次運行 function 會更改 function 內的數組

[英]Running a function more than once changes an array inside the function

下一個示例 function 工作得很好:

const data = [1, 2, 3, 4, 5];

function insertAndShift(arr, number) {
  const cutOut = arr.splice(-number);
  return [...cutOut, ...arr];
}

console.log('Output: ', insertAndShift(data, 2));
// Output: [4,5,1,2,3]

但是,當我再次調用 function 時,我突然得到了錯誤的響應:

const data = [1, 2, 3, 4, 5];

function insertAndShift(arr, number) {

  // The next starting array should be [1,2,3,4,5] on both occasions.
  // However, on the second occasion it will only be [1,2,3].
  // Which was the array in the first time the function was called.
  console.log('arr: ', arr);

  const cutOut = arr.splice(-number);
  return [...cutOut, ...arr];
}

console.log('Output: ', insertAndShift(data, 2));
// Output: [4,5,1,2,3]

console.log('Output: ', insertAndShift(data, 3));
// Output: [1,2,3]
// Should be: [3,4,5,1,2]

這是范圍界定問題嗎? 或者這里到底發生了什么?

在 Javascript 中,所有非原始變量都“通過引用”傳遞,這意味着您可以從 function 內部修改變量。 這是你需要小心的地方。 通常,您會先克隆您的陣列,然后再對其進行任何操作,這樣,原始陣列就不會受到您的突變的影響。

 const data = [1, 2, 3, 4, 5]; function insertAndShift(arr, number) { let clonedArray = [...arr]; // The next starting array should be [1,2,3,4,5] on both occasions. // However, on the second occasion it will only be [1,2,3]. // Which was the array in the first time the function was called. const cutOut = clonedArray.splice(-number); return [...cutOut, ...clonedArray]; } console.log('Output: ', insertAndShift(data, 2)); console.log('Output: ', insertAndShift(data, 3));

除了克隆數組之外,您還可以直接使用Array#slice部分並構建一個新數組 - 無需使用變異Array#splice

 function insertAndShift(array, number) { return [...array.slice(-number), ...array.slice(0, -number)]; } const data = [1, 2, 3, 4, 5]; console.log(...insertAndShift(data, 2)); // [4, 5, 1, 2, 3] console.log(...insertAndShift(data, 3)); // [3, 4, 5, 1, 2]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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