js怎么遍历数组中的对象的属性?

JavaScript011

js怎么遍历数组中的对象的属性?,第1张

具体代码如下所示:

1、<script>  //----------------for用来遍历数组对象;

2、 var i,myArr = [1,2,3]  for (var i = 0i <myArr.lengthi++) {    console.log(i+":"+myArr[i])  }

3、 //---------for-in 用来遍历非数组对象   var man ={hands:2,legs:2,heads:1}  //为所有的对象添加clone方法,即给内置原型(object,Array,function)增加原型属性,该方法很强大,也很危险   if(typeof Object.prototype.clone ==="undefined"){    Object.prototype.clone = function(){}   } ;

4、  //   for(var i in man){    if (man.hasOwnProperty(i)) { //filter,只输出man的私有属性     console.log(i,":",man[i])   }  }  ;

5、//输出结果为print hands:2,legs:2,heads:1   for(var i in man) {//不使用过滤    console.log(i,":",man[i])  }   ;

6、 //输出结果为://hands : 2 index.html:20   //legs : 2 index.html:20   //heads : 1 index.html:20   //clone : function ;

7、for(var i in man) {    if(Object.prototype.hasOwnProperty.call(man,i)) { //过滤     console.log(i,":",man[i])   }   };

8、 //输出结果为print hands:2,legs:2,heads:1 </script>   。

javaScript遍历对象总结:

1、

2、

很简单

$(".class").each(function (){ // 里面放class名字 把你想遍历的标签 class名改成一样的

$(this).val() //值

$(this).attr('id')// id属性

})

主要有三种方式,for...in 、Object.keys(obj)、Object.getOwnPropertyNames(obj):

<!DOCTYPE html>

<html>

<head>

<meta charset="UTF-8">

<title>遍历对象的几种方式</title>

</head>

<body>

</body>

<script>

const obj = {

a:1,

b:true,

c:"hello"

}

//方式1:for in方式  

for(let key  in obj){

        console.log(key)

   }

//Object.keys 方式 直接返回一个数组

console.log(Object.keys(obj))

console.log(Object.getOwnPropertyNames(obj))

</script>

</html>

如果想要了解他们具体的区别的话,可以看下这篇博客JS中三种主要的遍历对象的方法:for in、Object.