编写删除数组并添加到列表的函数
Writing a functions that removes an array and adds to the list
我目前正在freecodecamp学习Javascript,并且正在学习函数。
我正在执行一项任务,要求我更正一种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 函数应返回已删除的元素。
dr 你用的是Array.prototype.shift
,Array.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;
}
function nextInLine(arr, item) {
// Your code here
var queue = arr.push(item);
var removeItem = arr.shift();
return removeItem; // 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()
若要返回已删除的元素,请使用 return removeItem
并在使用 .shift()
方法设置 var 后使用
相关文章:
- Javascript通过列表项的函数和css来更改背景颜色
- 从javascript调用服务器端的下拉列表onchange函数
- 如何创建背景图像列表'URL,并使用jQuery在单击函数时应用它们
- 创建自定义函数以在函数上运行完整的多选下拉列表
- 是否可以在javascript函数参数列表中调用多个函数
- 为数组Jquery/Javascript创建一个列表函数
- 如何使用 couchdb 列表函数从 couchdb 视图结果中获取特定字段
- 如何在 SharePoint 上向此淘汰 JavaScript 添加额外的列表函数
- 语法错误:缺少参数列表函数 () {.
- XPages中的列表函数
- “compilation_error”在我的 CouchDB 设计文档中的列表函数中
- 是否可以在coucdhb列表函数中包含外部javascript代码
- 如何在列表函数中修复此闭包
- 在jquery对象的集合上使用underscore.js列表函数
- 调用couchdb中的另一个列表函数
- 返回和保留选择的下拉列表函数
- 数据库中的列表函数得到一个表达式不会计算为函数错误
- 使用本地存储的可排序列表函数出错
- 如何在列表函数中导入Javascript库
- jQuery播放列表函数错误:函数未定义