歡迎堆棧溢出:)
我也通過這個任務了作爲承擔自由編碼營前端認證的一部分。作爲參考,這是任務:https://www.freecodecamp.com/challenges/stand-in-line
寫功能nextInLine
它接受一個陣列(arr
)和多個 (item
)作爲參數。將數字添加到數組的末尾,然後 刪除數組的第一個元素。 nextInLine函數然後應該返回已被移除的元素 。
當你的解決方案提供了理想的結果,就可以解決這個任務沒有(在你的代碼firstItem
)聲明一個變量。我準備在這裏與說明演示給你:http://codepen.io/PiotrBerebecki/pen/xEYbgv
關鍵的東西是要明白:
的shift()方法刪除數組的第一個元素和回報 那個元素。此方法更改數組的長度。 https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/shift
function nextInLine(arr, item) {
// arr is now: [5,6,7,8,9]
arr.push(item); // add 10 to the and of array
// arr is now: [5,6,7,8,9,10]
return arr.shift(); // remove first element of arr (5)
// and then return this first element (5),
// arr is now [6,7,8,9,10]
}
var testArr = [5,6,7,8,9];
console.log(nextInLine(testArr, 10)); // 5
console.log("After: " + JSON.stringify(testArr)); // After: [6,7,8,9,10]
我建議你閱讀一下數組的變化 – Eric
你不必創建'firstItem'。你可以返回'arr.shift()'。所以'arr.push'將一個項目添加到數組的末尾,'shift'移除數組開始處的項目。 –
是的,您可以完成'return arr.shift(arr);' – Makyen