简体   繁体   中英

Iterating over a multilevel array

I have an array of values that can be cycled through using the next/prev buttons:

Example:

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>

Tell me please how to iterate over if the array is multidimensional?

I managed to make an example based on a one-dimensional array, but it does not work in the case of a multidimensional one

The next() and prev() functions just need a little logic to cycle two, dependent variables. The snippet below explains further:

 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... col = 0; //...and advance the row. if we're at its limit, reset it, too 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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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