This article mainly introduces the object looping method in jquery. Interested friends can refer to a friend who asks how to convert objects into arrays. When I ask him why he wants to convert objects, he told me that arrays can be traversed cyclically using js, but objects cannot. Actually, objects can be traversed cyclically. It can be cyclic without conversion! This shows that you are not very familiar with js or jquery operations! Here is a brief introduction!
Case
Let's look at the following objects:
Var data = {Zhang San: 69, Li Si: 72, Wang Wu: 90, Erma Zi: 88, front-end blog: 100, haorooms: 98, Wang dazhuang: 99}
Assume that the above is a key returned by the background and an object of value (this type of object is often encountered !), Now we need to link this content to a table in a loop. Some friends do not know how to operate the object loop! Today, I will introduce you to two methods!
Method 1:
Use $. each to loop!
If you do not know $. each, we recommend that you search for it online. Of course, you can also search for "jquery's $ (). each, $. each differences". I will not detail their differences here. Some friends may use the $ (). each method. Today we will introduce $. each.
$. Each () can traverse arrays and objects. The method is as follows:
$. Each ([{"name": "haorooms", "email": "bb@126.com" },{ "name": "qianduan", "email": "aa@hao.com"}], function (I, n) {alert ("index:" + I, "corresponds to:" + n. name );});
You can also traverse it like this:
var arr1 = [ “one”, “two”, “three”, “four”, “five” ];$.each(arr1, function(){alert(this);});
Output:One two three four five
The best thing is that you can traverse the array:
Var obj = data; // The data copied above $. each (obj, function (key, val) {alert (obj [key]); // You can output the result console. log (key); // output name });
Method 2:
Use a for in loop to traverse obj
For the above object, we can write this to loop!
For (var I in data) {console. dir (I); // output name console. dir (data [I]); // output score}
For in loop I believe everyone should be familiar with it! For loop we use more for (var I = 0; I
In addition, if we encounter the following objects:
Var data = {Zhang San: 69, Li Si: 72, Wang Wu: 90, Erma Zi: 88, front-end blog: 100, haorooms: 98, Wang dazhuang: 99}
We can use data. haorooms gets 98, but we use "data. "Front-end blog" will report an error. Therefore, when we use Chinese characters as the key value, we should use data ["front-end blog"] for selection, do not use the dot.
The above is the object looping method in jquery. I hope it will be helpful for your learning.