【问题标题】:Iterating over a multilevel array遍历多级数组
【发布时间】:2023-01-31 01:40:59
【问题描述】:

我有一组值,可以使用下一个/上一个按钮循环:

例子:

var sav = [
    "first item",
    "second item",
    "third item"
];

var box = document.getElementById('box');

var i = -1;

function next() {
    i = i >= sav.length - 1 ? 0 : i + 1;
    box.innerHTML = sav[i];
}

function prev() {
    i = i > 0 ? i - 1 : sav.length - 1;
    box.innerHTML = sav[i];
}

<a href="#" onclick="prev()">Previous</a>
<div id="box"></div>
<a href="#" onclick="next()">Next</a>

如果数组是多维的,请告诉我如何迭代?

我设法基于一维数组做了一个例子,但它在多维数组的情况下不起作用

【问题讨论】:

  • 显示的代码中似乎没有任何多维数组。
  • 请显示您的多维数组并说明您希望如何迭代和循环它。只是.flat()tening 吗?

标签: javascript multidimensional-array


【解决方案1】:

next()prev() 函数只需要一点逻辑来循环两个因变量。下面的 sn-p 进一步解释:

var sav = [
    ["0-a", "0-b", "0-c"],
    ["1-a", "1-b", "1-c"],
    ["2-a", "2-b", "2-c"],
];

const box = document.getElementById('box');
let row = 0, col = 0;
box.innerHTML = sav[row][col];

function next() {
    if (col === sav[row].length-1) {
      // if the col is at its limit, reset and advance the row
      col = 0;
      // if the row is at its limit, reset
      row = row === sav.length-1 ? 0 : row+1;
    } else { // otherwise, just advance the col
      col = col+1
    }
    box.innerHTML = sav[row][col]
}

function prev() {
    // same as above, except 0 is the limit, and we subtract to "advance"
    if (col === 0) {
      col = sav[row].length-1;
      row = row === 0 ? sav.length-1 : row-1;
    } else {
      col = col-1
    }
    box.innerHTML = sav[row][col]
}
<a href="#" onclick="prev()">Previous</a>
<div id="box"></div>
<a href="#" onclick="next()">Next</a>

【讨论】:

    猜你喜欢
    • 2012-04-16
    • 1970-01-01
    • 1970-01-01
    • 2017-12-25
    • 1970-01-01
    相关资源
    最近更新 更多