获取一个对象或数组的所有属性及值

一. for in 循环

1. 遍历对象

var person={fname:'John', sname:'Doe', age:25}
for (var x in person){
    console.log(x + '==' + person[x])
}

----------
fname==John
sname==Doe
age==25

2. 遍历数组

写法一:

for (var index = 0; index < myArray.length; index++) {
    console.log(myArray[index]);
}`

写法二:

for(var index in arr){
    console.log(arr[index])
}

注:遍历数组时,有以下三点需要注意

点1:

var arr=[1,2,3,4]
for(var index in arr){
    console.log(arr[index]+2)
}

----------
3
4
5
6

点2:

var arr=['name','age','gender']
for(var index in arr){
    console.log(arr[index]+2)
}


----------
name2
age2
gender2

点3:

var arr=[1,2,3,4]
for(var index in arr){
    console.log(index+2)
}


----------
02
12
22

有人说:在某些情况下,上面代码将会以任意顺序去遍历数组元素,即显示顺序并不是按我们所想的那样。(有待验证)
因此,for-in 设计的目的是用于遍历包含键值对的对象,对数组并不是那么友好。
遍历数组的话还是用es6的for of循环遍历比较好,改天介绍一下。(有待了解)

二. for each

myArray.forEach(function (value) {
    console.log(value);
});

三. jQuery.each

//遍历数组
var arr = ["one", "two", "three", "four", "five"];  
var text = "Array ";  
jQuery.each(arr, function(i, val) {  
    text = text + " #Index:" + i + ":" + val;  
});  
console.log(text);  
----------
Array  #Index:0:one #Index:1:two #Index:2:three #Index:3:four #Index:4:five  

//遍历对象
var obj = { one: 1, two: 2, three: 3, four: 4, five: 5 };  
text = "Object ";  
jQuery.each(obj, function(i, val) {  
    text = text + "Key:" + i + ", Value:" + val; 
});  
console.log(text);  
----------
Object Key:one, Value:1Key:two, Value:2Key:three, Value:3Key:four, Value:4Key:five, Value:5 

猜你喜欢

转载自blog.csdn.net/love_parents/article/details/81941591
今日推荐