【发布时间】:2026-01-17 02:05:02
【问题描述】:
在这个问题中,我被要求编写一个函数 nextInLine,它接受一个数组 (arr) 和一个数字 (item) 作为参数。将数字添加到数组的末尾,然后删除数组的第一个元素。然后 nextInLine 函数应该返回被移除的元素。
这里是sn-p:
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));
如何使这段代码工作?提前致谢!
【问题讨论】:
-
您可以使用
push()函数添加到数组的末尾,并使用shift()删除并返回第一个元素。 -
你能告诉我整个代码吗?我一直在尝试使用 push() 方法来附加最后一个元素和 shift() 方法来删除第一个元素。但它显示我的函数 nextInLine() 并没有按照预期的方式提供所需的输出!
-
我见过! :) 具有讽刺意味的是,如果尝试了这个类似的代码.. 但它没有按预期工作! :( 以下检查正确:1) nextInLine([2], 1) 应该返回 2 2) nextInLine([5,6,7,8,9], 1) 应该返回 5 3) 在 nextInLine(testArr, 10), testArr[4] 应该是 10 但不是以下... 4) nextInLine([], 1) 应该返回 1
-
@SidratulMuntahaIbneRahman 将所有这些要求放在问题中,而不是评论。
标签: javascript function queue