search
HomeWeb Front-endFront-end Q&AWhat are the methods for traversing objects and arrays in es6

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.

What are the methods for traversing objects and arrays in es6

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);
})

What are the methods for traversing objects and arrays in es6

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'];

5. filter()

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;如果后面的参数是个字符串,那么就是会是字符串拼接、

7, every (and)

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

8, some (or)

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 tutorialwebfrontend

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!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
CSS: Is it bad to use ID selector?CSS: Is it bad to use ID selector?May 13, 2025 am 12:14 AM

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: Goals in 2024HTML5: Goals in 2024May 13, 2025 am 12:13 AM

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

What are the main areas where HTML5 tried to improve?What are the main areas where HTML5 tried to improve?May 13, 2025 am 12:12 AM

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

CSS ID and Class: common mistakesCSS ID and Class: common mistakesMay 13, 2025 am 12:11 AM

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

What is thedifference between class and id selector?What is thedifference between class and id selector?May 12, 2025 am 12:13 AM

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

CSS IDs vs Classes: The real differencesCSS IDs vs Classes: The real differencesMay 12, 2025 am 12:10 AM

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

CSS: What if I use just classes?CSS: What if I use just classes?May 12, 2025 am 12:09 AM

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 in CSS: A Beginner's GuideID and Class Selectors in CSS: A Beginner's GuideMay 12, 2025 am 12:06 AM

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.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Article

Hot Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

mPDF

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),