免责声明:我是一名新手程序员,我并不是在寻找有人为我编写代码。我正在寻找可以修改以满足我的需要的指针或示例。如果有人为我做所有的工作,我还能学到什么? :=)
问题:我有一个如下所示的二维数组:
var myArray = [["pat", "tom" , "john"], ["sam", "toby", "barbra"],["william","jack", "janice"]];
我需要将数组从一行移动到下一行。 (我将对行进行更改。我已经编写了该代码并且它可以工作)。
我找到了以下代码,它应该允许我在数组中移动。向前移动(下一行)、向后移动(上一行)和当前位置。
var iterifyArr = function (arr) {
var cur = 0;
arr.nextRecord = (function () { return (++cur >= this.length) ? false : this[cur]; });// move to the next row of array
arr.prevRecord = (function () { return (--cur <= this.length) ? false : this[cur]; });//move to previous row of array
arr.cur = (function () { return this[cur]; });
return arr;
};
var myArray = [["pat", "tom" , "john"], ["sam", "toby", "barbra"],["william","jack", "janice"]];
iterifyArr(myArray);
当我尝试使用以下代码获取当前位置时,我得到的是行的最后一个位置,而不是行号本身。
var currentpos = myStack.cur();
有人可以指出我在这方面出错的地方吗?
最佳答案
我建议保留 cur
,我将其重命名为 index
在有效位置。这意味着在增加或减少之前进行检查。
function iterifyArr(arr) {
var index = 0;
arr.nextRecord = function () {
return index + 1 < this.length && this[++index];
};
arr.prevRecord = function () {
return index >= 1 && this[--index];
};
arr.currentRecord = function () {
return this[index];
};
arr.getIndex = function () {
return index;
};
return arr;
};
var myArray = [["pat", "tom", "john"], ["sam", "toby", "barbra"], ["william", "jack", "janice"]];
iterifyArr(myArray);
console.log(myArray.nextRecord());
console.log(myArray.nextRecord());
console.log(myArray.nextRecord());
console.log(myArray.currentRecord());
console.log(myArray.getIndex());
.as-console-wrapper { max-height: 100% !important; top: 0; }
关于javascript - 在二维数组中前后移动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41017700/