Home > Article > Web Front-end > How to operate JS to traverse multi-dimensional arrays
This time I will show you how to operate JS to traverse multi-dimensional arrays, and what are the precautions for operating JS to traverse multi-dimensional arrays. The following is a practical case, let's take a look. z
Go directly to the text:
Sometimes when we process data, we may encounter some irregularities (unpredictable data structures), so how do we perform traversal operations when we get 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} }
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)
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:
I believe you have mastered the method after reading the case in this article, and more How exciting, please pay attention to other related articles on php Chinese website!
Recommended reading:
JS callback function using parameters
Use iview’s ui framework to customize the player
The above is the detailed content of How to operate JS to traverse multi-dimensional arrays. For more information, please follow other related articles on the PHP Chinese website!