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!

To integrate React into HTML, follow these steps: 1. Introduce React and ReactDOM in HTML files. 2. Define a React component. 3. Render the component into HTML elements using ReactDOM. Through these steps, static HTML pages can be transformed into dynamic, interactive experiences.

React’s popularity includes its performance optimization, component reuse and a rich ecosystem. 1. Performance optimization achieves efficient updates through virtual DOM and diffing mechanisms. 2. Component Reuse Reduces duplicate code by reusable components. 3. Rich ecosystem and one-way data flow enhance the development experience.

React is the tool of choice for building dynamic and interactive user interfaces. 1) Componentization and JSX make UI splitting and reusing simple. 2) State management is implemented through the useState hook to trigger UI updates. 3) The event processing mechanism responds to user interaction and improves user experience.

React is a front-end framework for building user interfaces; a back-end framework is used to build server-side applications. React provides componentized and efficient UI updates, and the backend framework provides a complete backend service solution. When choosing a technology stack, project requirements, team skills, and scalability should be considered.

The relationship between HTML and React is the core of front-end development, and they jointly build the user interface of modern web applications. 1) HTML defines the content structure and semantics, and React builds a dynamic interface through componentization. 2) React components use JSX syntax to embed HTML to achieve intelligent rendering. 3) Component life cycle manages HTML rendering and updates dynamically according to state and attributes. 4) Use components to optimize HTML structure and improve maintainability. 5) Performance optimization includes avoiding unnecessary rendering, using key attributes, and keeping the component single responsibility.

React is the preferred tool for building interactive front-end experiences. 1) React simplifies UI development through componentization and virtual DOM. 2) Components are divided into function components and class components. Function components are simpler and class components provide more life cycle methods. 3) The working principle of React relies on virtual DOM and reconciliation algorithm to improve performance. 4) State management uses useState or this.state, and life cycle methods such as componentDidMount are used for specific logic. 5) Basic usage includes creating components and managing state, and advanced usage involves custom hooks and performance optimization. 6) Common errors include improper status updates and performance issues, debugging skills include using ReactDevTools and Excellent

React is a JavaScript library for building user interfaces, with its core components and state management. 1) Simplify UI development through componentization and state management. 2) The working principle includes reconciliation and rendering, and optimization can be implemented through React.memo and useMemo. 3) The basic usage is to create and render components, and the advanced usage includes using Hooks and ContextAPI. 4) Common errors such as improper status update, you can use ReactDevTools to debug. 5) Performance optimization includes using React.memo, virtualization lists and CodeSplitting, and keeping code readable and maintainable is best practice.

React combines JSX and HTML to improve user experience. 1) JSX embeds HTML to make development more intuitive. 2) The virtual DOM mechanism optimizes performance and reduces DOM operations. 3) Component-based management UI to improve maintainability. 4) State management and event processing enhance interactivity.


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

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

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

Dreamweaver Mac version
Visual web development tools

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 Chinese version
Chinese version, very easy to use

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