javascript traverse object, array summary

 

In the process of daily work, we operate very frequently in javaScript to traverse objects and arrays. Today, we take the time to summarize the frequently used methods for future reference!

    javascript traversal object summary

1. Use Object.keys() to traverse and  

return an array, including all enumerable properties of the object itself (excluding inherited) (excluding Symbol properties).
copy code
var obj = {'0':'a','1':'b','2':'c' };

Object.keys(obj).forEach(function(key){

     console.log(key,obj[key]);

});
copy code

 

 

 

2. Use the for.. in .. traversal      

loop to traverse the object's own and inherited enumerable properties (excluding the Symbol property).
copy code
var obj = {'0':'a','1':'b','2':'c' };

for(var i in obj) {

     console.log(i,":",obj[i]);

}

 
copy code

 

 

 

3. Use Object.getOwnPropertyNames(obj) to traverse

      Returns an array containing all properties of the object itself (excluding Symbol properties, but including non-enumerable properties).
copy code
var obj = {'0':'a','1':'b','2':'c' };
Object.getOwnPropertyNames(obj).forEach(function(key){

    console.log(key,obj[key]);

});
copy code

 

 

4、使用Reflect.ownKeys(obj)遍历

      返回一个数组,包含对象自身的所有属性,不管属性名是Symbol或字符串,也不管是否可枚举.  
copy code
var obj = {'0':'a','1':'b','2':'c'};
Reflect.ownKeys(obj).forEach(function(key){

console.log(key,obj[key]);

});
copy code

 

 

 

javaScript遍历数组总结

 

1、使用forEach遍历
copy code
var arr=[1,2,3,4];

arr.forEach(function(val, index) {

console.log(val, index);
});

 
copy code

 

 

 

2、使用for..in..遍历
copy code
var arr=["张三","李四","王五","赵六"];

for (var i in arr){

console.log(i,":",arr[i]);

}
copy code

 

 

3. Use for- of traversal

     Not only arrays, but also most array-like objects, such as DOM NodeList objects.

     String traversal is also supported, which traverses a string as a sequence of Unicode characters.
copy code
var arr=["Zhang San", "Li Si", "Wang Wu", "Zhao Liu" ];

for (var value of arr){

    console.log(value);

}
copy code

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325701147&siteId=291194637