Home > Web Front-end > JS Tutorial > How to implement traversal of irregular multi-dimensional arrays in JS

How to implement traversal of irregular multi-dimensional arrays in JS

亚连
Release: 2018-05-26 17:31:14
Original
1869 people have browsed it

This article mainly introduces the method of JS to implement traversal of irregular multi-dimensional arrays, involving the implementation and usage skills of recursive traversal of javascript arrays. Friends in need can refer to it

The example of this article tells the implementation of JS to traverse irregular multi-dimensional arrays Methods for regular multidimensional arrays. Share it with everyone for your reference, the details are as follows:

Go directly to the text:

Sometimes when we process data, we may encounter some irregularities (unpredictable data structures), then get How do we traverse this kind of data? For example:

var data= {
    a: { one: 1, two: 2, three: {four:'2',five:'4'} },
    b: { six: 4, seven: 5, eight: 6 },
    c: { nine: 7, ten: 8}
}
Copy after login

For example, the data above (the actual situation is that this data will have various unpredictable changes), if you want to traverse this kind of data, you cannot traverse it with a simple for in.

In fact, this kind of data traversal is also simple. Using the recursive method can perfectly solve this problem.

The code is as follows:

function traverse(obj) {
    for (var a in obj) {
      if (typeof(obj[a]) == "object") {
        traverse(obj[a]); //递归遍历
      } else {
        console.log(a + "=" + obj[a]); //如果是值就显示
      }
    }
}
traverse(data)
Copy after login

Finally, we only need to call this method to When obj is passed in, the entire data is successfully traversed

The results of this example are as follows:

The above is what I compiled for everyone. I hope it will be useful to you in the future. Everyone is helpful.

Related articles:

Introduction to the 4 common request methods of ajax in jQuery

How to use native ajax to process json strings

Let’s talk about our views and understanding of Ajax form submission

The above is the detailed content of How to implement traversal of irregular multi-dimensional arrays in JS. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template