Methods for traversing objects: 1. "for in" statement, which can loop through the object's own and inherited enumerable properties; 2. Object.keys() and Object.values(); 3. Object .getOwnPropertyNames(). Methods for traversing the array: 1. forEach(), which can call a function for each element in the array; 2. map(), which calls the specified callback function for each element of the array; 3. filter(); 4. some ()etc.
The operating environment of this tutorial: Windows 7 system, ECMAScript version 6, Dell G3 computer.
We often use array or object traversal in our work. One of the pain points of for is that additional variables are defined. When there are too many for loops, variables are prone to conflict. ES6 provides a new traversal method. Let’s take a look at
Traversing objects
1, for (let k in obj) {}
Loop through the object's own and inherited enumerable propertiesProperties
(Loop through the object's own and inherited enumerable properties (excluding Symbol properties)
let obj = {'0':'a','1':'b','2':'c'} for (let k in obj) { console.log(k+':'+obj[k]) } //0:a //1:b //2:c
2, Object.keys(obj)
|| Object.values(obj)
Returns a traversal object attribute or attribute value The array
(excluding the Symbol attribute). The
Object.keys() method will return an array consisting of the self-enumerable properties of a given object , the order of the attribute names in the array is consistent with the order returned when the object is traversed normally.
Object.values() method returns all the enumerable properties of a given object itself An array of values, in the same order as using a for...in loop (the difference is that the for-in loop enumerates the properties in the prototype chain).
let obj = {'0':'a','1':'b','2':'c'} console.log(Object.keys(obj)) //["0","1","2"] console.log(Object.values(obj)) //["a","b","c"]
3. Object.getOwnPropertyNames(obj)
Returns an array that traverses the object properties or property values (excluding Symbol properties, self properties - excluding properties on the prototype) .
let obj = {'0':'a','1':'b','2':'c'}; Object.getOwnPropertyNames(obj).forEach(function(key){ console.log(key,obj[key]); }); // 0 a // 1 b // 2 c
Traverse the array
1, arr.forEach
Note that the parameter is a Anonymous function, and the first parameter is the value of the array member, and the second parameter is their index.
var name = ['张三', '李四', '王五']; ['张三', '李四', '王五'].forEach((v,l,k) => { console.log(v); console.log(l); console.log(k); })
2、for(let k in arr){}
let arr = ['a','b','c','d'] for(let k in arr){ console.log(k,arr[k]) } // 0 a // 1 b // 2 c // 3 d
k is the index value of each array member.
3、for(let k of arr){ }
k is the value of each array member.
not only supports arrays, but also supports most array-like objects (pseudo-arrays) , such as DOM NodeList object.
also supports string traversal, which treats strings as a series of Unicode characters for traversal.
let arr = ['a','b','c','d'] for(let k of arr){ console.log(k) } // a // b // c // d
4. map():
map represents mapping, that is, one-to-one correspondence. After the traversal is completed, a new array will be returned, but the original array will not be modified.
var a1 = ['a', 'b', 'c']; var a2 = a1.map(function(item,key,ary) { return item.toUpperCase(); }); console.log(a1);// ['a','b','c']; console.log(a2); //['A','B','C'];
It means filtering, which means it is a filter, so how to use it
var a1 = [1,2,3,4,5,6]; var a2 = a1.filter(function(item) { return item <p><a id="reduce__41"></a><strong>6. reduce()</strong></p><p>Traverse from left to right, generally used for addition, subtraction, multiplication and division </p><pre class="brush:php;toolbar:false">var a1 = [1, 2, 3]; var total = a1.reduce(function(first, second) { return first + second; },0); console.log(total) // Prints 6 //注意 1、就是 return first+second 其实相当于 return first+=second; 也就是说每次的first 是上一次的和 //2、就是function{}后面的参数,如果 有值 那么第一次加载的时候 first = 0; second = 1; 如果没有值 , first = 1 , second = 2;如果后面的参数是个字符串,那么就是会是字符串拼接、
function isNumber(value){ return typeof value == 'number'; } var a1 = [1, 2, 3]; console.log(a1.every(isNumber)); // logs true var a2 = [1, '2', 3]; console.log(a2.every(isNumber)); // logs false //注意:数组中每一个元素在callback上都被返回true时就返回true,否则为false
function isNumber(value){ return typeof value == 'number'; } var a1 = [1, 2, 3]; console.log(a1.some(isNumber)); // logs true var a2 = [1, '2', 3]; console.log(a2.some(isNumber)); // logs true var a3 = ['1', '2', '3']; console.log(a3.some(isNumber)); // logs false //注意:只要数组中有一项在callback上被返回true,就返回true
[Related recommendations: javascript video tutorial、webfrontend】
The above is the detailed content of What are the methods for traversing objects and arrays in es6. For more information, please follow other related articles on the PHP Chinese website!

Using ID selectors is not inherently bad in CSS, but should be used with caution. 1) ID selector is suitable for unique elements or JavaScript hooks. 2) For general styles, class selectors should be used as they are more flexible and maintainable. By balancing the use of ID and class, a more robust and efficient CSS architecture can be implemented.

HTML5'sgoalsin2024focusonrefinementandoptimization,notnewfeatures.1)Enhanceperformanceandefficiencythroughoptimizedrendering.2)Improveaccessibilitywithrefinedattributesandelements.3)Addresssecurityconcerns,particularlyXSS,withwiderCSPadoption.4)Ensur

HTML5aimedtoimprovewebdevelopmentinfourkeyareas:1)Multimediasupport,2)Semanticstructure,3)Formcapabilities,and4)Offlineandstorageoptions.1)HTML5introducedandelements,simplifyingmediaembeddingandenhancinguserexperience.2)Newsemanticelementslikeandimpr

IDsshouldbeusedforJavaScripthooks,whileclassesarebetterforstyling.1)Useclassesforstylingtoallowforeasierreuseandavoidspecificityissues.2)UseIDsforJavaScripthookstouniquelyidentifyelements.3)Avoiddeepnestingtokeepselectorssimpleandimproveperformance.4

Classselectorsareversatileandreusable,whileidselectorsareuniqueandspecific.1)Useclassselectors(denotedby.)forstylingmultipleelementswithsharedcharacteristics.2)Useidselectors(denotedby#)forstylinguniqueelementsonapage.Classselectorsoffermoreflexibili

IDsareuniqueidentifiersforsingleelements,whileclassesstylemultipleelements.1)UseIDsforuniqueelementsandJavaScripthooks.2)Useclassesforreusable,flexiblestylingacrossmultipleelements.

Using a class-only selector can improve code reusability and maintainability, but requires managing class names and priorities. 1. Improve reusability and flexibility, 2. Combining multiple classes to create complex styles, 3. It may lead to lengthy class names and priorities, 4. The performance impact is small, 5. Follow best practices such as concise naming and usage conventions.

ID and class selectors are used in CSS for unique and multi-element style settings respectively. 1. The ID selector (#) is suitable for a single element, such as a specific navigation menu. 2.Class selector (.) is used for multiple elements, such as unified button style. IDs should be used with caution, avoid excessive specificity, and prioritize class for improved style reusability and flexibility.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Dreamweaver CS6
Visual web development tools

WebStorm Mac version
Useful JavaScript development tools

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),
