2017-02-15 77 views
0

返回從數組中取出的值我試圖從arr.shift()中獲取我正在從數組中除去的值,並且我需要返回該值,我該如何去做這個?如何通過使用.shift()

function nextInLine(arr, item) { 
    // Your code here 
    arr.push(item); 
    arr.shift(); 

    return arr; // 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)); 
+1

'return arr.shift()'在一行中完成。用你當前的代碼,你需要將'.shift()'的結果存儲在一個變量中,然後返回變量 – 2017-02-15 00:45:25

+1

_return that value_是什麼意思?從函數返回它還是將它返回給數組? –

回答

1

的值分配給變量

function nextInLine(arr, item) { 
    // Your code here 
    arr.push(item); 
    var tmp = arr.shift(); 

    return tmp; 
} 

或替代地

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

    return arr.shift(); 
} 
3

只是返回arr.shift();

實施例:

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

默認情況下,數組移位移除數組的第一個元素,並且返回相同的數組。因此,正如前面的答案所述,「return arr.shift()」將返回從數組中移除的元素。

注意:shift()類似於array的pop()函數。唯一的不同是pop刪除了數組的最後一個索引(array-1的長度)的元素,而shift則刪除了第一個索引(0)的元素。但是,pop和shift會返回被刪除的元素。