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).
var obj = {'0':'a','1':'b','2':'c' }; Object.keys(obj).forEach(function(key){ console.log(key,obj[key]); });
2. Use the for.. in .. traversal
loop to traverse the object's own and inherited enumerable properties (excluding the Symbol property).
var obj = {'0':'a','1':'b','2':'c' }; for(var i in obj) { console.log(i,":",obj[i]); }
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).
var obj = {'0':'a','1':'b','2':'c' }; Object.getOwnPropertyNames(obj).forEach(function(key){ console.log(key,obj[key]); });
4、使用Reflect.ownKeys(obj)遍历
返回一个数组,包含对象自身的所有属性,不管属性名是Symbol或字符串,也不管是否可枚举.
var obj = {'0':'a','1':'b','2':'c'}; Reflect.ownKeys(obj).forEach(function(key){ console.log(key,obj[key]); });
javaScript遍历数组总结
1、使用forEach遍历
var arr=[1,2,3,4]; arr.forEach(function(val, index) { console.log(val, index); });
2、使用for..in..遍历
var arr=["张三","李四","王五","赵六"]; for (var i in arr){ console.log(i,":",arr[i]); }
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.
var arr=["Zhang San", "Li Si", "Wang Wu", "Zhao Liu" ]; for (var value of arr){ console.log(value); }