2017-05-15 42 views
0

我是Javascript新手。目前採取的任務在Javascript中,我有一個queue.Here的工作任務:項目可以添加在隊列後面,舊項目從隊列前面取下

寫一個函數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
+2

您應該domyhomeworkforme.com發佈此 - stackov erflow.com是針對特定問題的。要在這裏獲得幫助,您需要發佈您的工作。 – Malvolio

+5

您將對Array方法'.push'和'.shift'感興趣。在MDN上研究它們,你應該能夠從那裏拿走它。 –

回答

2

你應該試試這個:

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)); 
1

DEMO

function nextInLine(arr, item) { 
 
    arr.push(item); 
 
    return arr.shift(); 
 
} 
 

 
console.log(nextInLine([], 1)); // 1 
 
console.log(nextInLine([2], 1)); // 2 
 
console.log(nextInLine([5,6,7,8,9], 1)); // 5

相關問題