首先了解一下js数组中的东西:
1. push()方法可以在数组的末属添加一个或多个元素
2. shift()方法把数组中的第一个元素删除
3. unshift()方法可以在数组的前端添加一个或多个元素
4. pop()方法把数组中的最后一个元素删除
function nextInLine(arr, item) {
// Your code here
arr.push(item);
var removed = arr.shift();
return removed; // Change this line
}
// Test Setup
var testArr = [1,2,3,4,5];
// Display Code
console.log("Before: " + JSON.stringify(testArr));
console.log(nextInLine(testArr, 6)); // Modify this line to test
console.log("After: " + JSON.stringify(testArr));
这个是我在freecodecamp闯关游戏里面的一关,闯关要求是:
nextInLine([], 5)
should return a number.nextInLine([], 1)
should return 1nextInLine([2], 1)
should return 2nextInLine([5,6,7,8,9], 1)
should return 5After nextInLine(testArr, 10)
,testArr[4]
should be 10
而这道题要求nextInLine
函数应该返回被删除的元素,一开始我很纠结这种要怎么写,后来看了提示才知道。
所以解决这道题一共要分为三步:
1. 利用 arr.push(item);将数字添加到数组的末尾。
2. 再利用 shift()方法删除数组的第一个元素。
3. 再将return item改为return removed返回删除的元素。
按照这三步,然后这道题就可以解决了~