我是Java语言的新手。目前正在用Javascript进行任务,我必须在队列中工作。这是任务:


  编写一个nextInLine函数,该函数接受一个数组(arr)和一个数字
  (项目)作为参数。将数字添加到数组的末尾,然后
  删除数组的第一个元素。然后,nextInLine函数
  返回已删除的元素。


function nextInLine(arr, item) {
  // Your code here

  return item;  // 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));



  结果应该是这样的:



nextInLine([], 1)应该返回1
nextInLine([2], 1)应该返回2
nextInLine([5,6,7,8,9], 1)应该返回5
nextInLine(testArr, 10)之后,testArr[4]应该为10

最佳答案

您应该尝试这样:

function nextInLine(arr, item) {
  // Your code here
  arr.push(item);
  var returnable_value = arr[0];
  arr.shift();
  return returnable_value;  // Change this line
}

// Test Setup
var testArr = [1,2,3,4,5];

// Display Code
console.log("Before: " + JSON.stringify(testArr));
console.log(nextInLine(testArr, 10)); // Modify this line to test
console.log("After: " + JSON.stringify(testArr));
console.log(nextInLine(testArr, 4));

08-16 06:03