如何使用.push和.shift使用函数修改数组并对其进行排队



基本上,我需要知道如何在队列中移动数组,以便去掉"1'"并添加"6"。我已经知道要做到这一点,我需要使用.push()和.shift()元素。然而,我对如何做到这一步感到困惑。特别是如何构建代码,以及告诉.push和.shiff()看什么。例如"blank.push);".我得到的最远的结果是在函数中包含"arr.push()"one_answers"arr.shift()",但所做的只是去掉了"1"。我还需要知道为什么以及我需要更改"return item;"行到。下面是提供给我的代码。

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

如果你只想提供一个有效的解决方案,我应该能够了解它的作用,并找出它的作用方式和原因,但我非常感谢对"//显示代码"行以上的所有内容尽可能详细地解释此代码中发生的事情。我对JS有一些工作知识,但你认为我知道的越少,我就会越开心。:)

奖金回合:只是好奇,但如果有人能告诉我为什么"arr.shift()"是可接受的代码(无论它是函数),但"item.push()"或"item.shift)"错误为"TypeError:item.push不是函数"。对我来说,它们都是这个函数的相似参数。为什么一个出错而另一个没有?"arr"或我不知道的特质是否有程序化的含义?

function nextInLine(arr, item) {
var nextItem = arr.shift(); // This removes the first element of the array, being 1, and assigns it to the nextItem variable.
// Now arr = [2,3,4,5]
arr.push(item); // This adds the item 6 to the end of the queue
// Now arr = [2,3,4,5,6]
return nextItem;
}

奖金答案:
本文中的arr是一个数组,它有push和shift方法。
项目是一个数字,它没有这样的方法

function nextInLine(arr, item) {
// Your code here
arr.shift();
arr.push(item);
return item;  // Change this line
}

最新更新