欢迎堆栈溢出:)
我也通过这个任务了作为承担自由编码营前端认证的一部分。作为参考,这是任务: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