JavaScript对象遍历
一、对象是数组:
var arr = [9, 8, 7, 6, 5, 4, 3, 2, 1]; //each遍历: $.each(arr,function (index,value) { alert(index) }) //0 1 2 3 4 5 6 7 8 $.each(arr,function (index,value) { alert(value) }) //9 8 7 6 5 4 3 2 1 $.each(arr,function () { alert(this) }) //9 8 7 6 5 4 3 2 1
//for遍历:
for (var i in arr) { //不推荐for in 遍历数组
console.log(arr[i]);
} //9 8 7 6 5 4 3 2 1
for (var i = 0; i < arr.length; i++) {
console.log(arr[i]);
} //9 8 7 6 5 4 3 2 1
var arr = [{"id":"1","tagName":"apple"},{"id":"2","tagName":"orange"},{"id":"3","tagName":"banana"},{"id":"4","tagName":"watermelon"},{"id":"5","tagName":"pineapple"}]; $.each(arr, function(index, obj) { alert(index); // 0,1,2,3,4 alert(obj); //{"id":"1","tagName":"apple"},{"id":"2","tagName":"orange"}... alert(obj.id); // 1,2,3,4,5 alert(obj.tagName); // apple, orange, banana, watermelon, pineapple }); $.each(arr, function(index, obj) { alert("第"+ index +"项的tagName是"+obj.tagName); }); //第0项的tagName是apple 第1项的tagName是orange..................
二、对象是json:
var json = { "jim": "11", "tom": "12", "lilei": "13" }; //jquery获取 $.each(json , function(key, value) { alert(key); //jim tom lilei alert(value); //11 12 13 }); //原生JS获取 for(var i in json){ alert(i); //jim tom lilei alert(json[i]); //11 12 13 };
三、json是字符串:(解决方案:JSON字符串转换为JavaScript对象。)
var json = '[{"id":"1","tagName":"apple"},{"id":"2","tagName":"orange"},{"id":"3","tagName":"banana"},{"id":"4","tagName":"watermelon"},{"id":"5","tagName":"pineapple"}]'; //用$.parseJSON(json)或者JSON.parse(json)将其转换为JavaScript对象 字符串转json对象 $.each($.parseJSON(json), function(idx, obj) { alert(obj.tagName); //apple, orange, banana, watermelon, pineapple });
json的解析方法共有两种:eval() 和 JSON.parse(),使用方法如下:
var jsonData = '{"data1":"Hello", "data2":"world"}'; eval("("+jsonData+")"); //Object {data1: "Hello", data2: "world"} JSON.parse(jsonData); //Object {data1: "Hello", data2: "world"}
这样就把jsonData这个json格式的字符串转换成了JSON对象。
eval("("+data+")"); //转换为json对象
eval在解析字符串时,会执行该字符串中的代码(这样的后果是相当恶劣的)
var obj= [{"id":"1","tagName":"apple"},{"id":"2","tagName":"orange"},{"id":"3","tagName":"banana"},{"id":"4","tagName":"watermelon"},{"id":"5","tagName":"pineapple"}]; JSON.stringify(obj) //json对象转字符串 与JSON.parse()相反 "[{"id":"1","tagName":"apple"},{"id":"2","tagName":"orange"},{"id":"3","tagName":"banana"},{"id":"4","tagName":"watermelon"},{"id":"5","tagName":"pineapple"}]"