繁体   English   中英

编写一个删除数组并添加到列表的函数

[英]Writing a functions that removes an array and adds to the list

我目前正在 freecodecamp 学习 Javascript,并且正在学习函数。

我正在执行一项任务,要求我纠正一种queue类型,该queue将从数组中删除第一个项目,并将其替换为另一个(在数组末尾)。

这是我到目前为止所拥有的:

function nextInLine(arr, item) {
  // Your code here
  array = [];
  array.shift(arr);
  array.push(item);
  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, 2, 3, 4, 5]

之后:[1, 2, 3, 4, 5]

当所有人都出去时我很困惑..我将如何完成这项任务?

实际任务:

在计算机科学中,队列是一种抽象的数据结构,其中项目按顺序排列。 可以在队列后面添加新项目,从队列前面删除旧项目。

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

tl;dr 你使用Array.prototype.shiftArray.prototype.push错误的。

shift从数组中删除第一个项目并返回该项目。 而不是

array = [];
array.shift(arr);

你想做

var firstItem = arr.shift();

push将一个项目添加到数组的末尾。 您想原地改变原始数组对象,所以您想这样做

arr.push(item);

然后返回第一项

return firstItem;

这为您提供了以下功能:

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

如果要修改传递的数组,则应在其上运行所有命令。

function nextInLine(arr, item) {
  // Your code here
  arr.shift();
  arr.push(item);
  return arr;  // this line is only required if you want to assign to a new array at the same time
}
function nextInLine(arr, item) 
{ 
    // Your code here arr.push(item); 
    return item = arr.shift(); 
    // return item; 
    // Change this line 
}

试试这个:-

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM