Traversal of JavaScript collection type data structure

1 Overview

The most frequently used data structures in JavaScript are nothing more than Array and Object, and traversing them is very frequent in daily work. In ES6, the Set and Map data structures are added, and the traversal methods are similar.
In actual work, the background program reads the database to obtain list data, and after returning to the front-end, the front-end needs to render and display, such as product list data:

  • Multiple product lists are received through an array, and each element of the array is a product object.
  • The name, attribute, status of the product on and off the shelf, whether it is discounted, etc. are the attributes of the product object.

2. Array - Array

An array is an ordered collection of values. Each value in the array is called an element, and each element has a numerical position in the array, called an index. The index starts from 0 and increases sequentially. In JavaScript, you can use the Array object to define an array. In addition, the Array object also provides various properties and methods related to the array.

for

The number of traversals is determined by the length of the array.


let cars = ["Benz", "BMW", "Lexus"];
// 方式1:for
    for (let i = 0; i < cars.length; i++) {
    
    
        console.log(`for遍历下:第 ${
      
      i} 的值: ${
      
      cars[i]}`)
    }
    

forEach


let cars = ["Benz", "BMW", "Lexus"];
// 方式2:forEach
	cars.forEach(function (value, index) {
    
    
		console.log(`forEach遍历下:第 ${
      
      index} 的值: ${
      
      value}`)
	});
	

for…of…


let cars = ["Benz", "BMW", "Lexus"];
// 方式3:for...of...
	for (let car of cars) {
    
    
		console.log(`for...of遍历下: ${
      
      car}`)
	}
	

for…in


let cars = ["Benz", "BMW", "Lexus"];
// 方式4:for...in
    for (let index in cars) {
    
    
		console.log(`for...in遍历下: ${
      
      cars[index]}`)
    }
    

ES6 - keys()


let cars = ["Benz", "BMW", "Lexus"];
// 方式5:ES6 - keys()
    for (let index of cars.keys()) {
    
    
		console.log(`ES6 - keys 遍历下:第 ${
      
      index} 的值: ${
      
      cars[index]}`)
    }

ES6 - values()


// 方式6:ES6 - values()
	for (let car of cars.values()) {
    
    
		console.log(`ES6 - values 遍历下:${
      
      car}`)
	}

ES6 - entries()


let cars = ["Benz", "BMW", "Lexus"];
// 方式7:ES6 - entries()
	for (let [index, car] of cars.entries()) {
    
    
		console.log(`ES6 - keys 遍历下:第 ${
      
      index} 的值: ${
      
      car}`)
	}
	

3. Object - Object

JavaScript is an object-oriented programming language, and almost everything in JavaScript is an object. Therefore, to use JavaScript effectively, you first need to understand how objects work and how to create and use them.

We can think of an object as an unordered collection of properties, each of which has a name and a value (key/value pair). We know from the section "JS Data Types" that an array is a collection of values, and each value has a numerical index (starting from zero and increasing in sequence). An object is similar to an array, the difference is that the index in the object is customized, such as name (name), age (age), gender (sex), etc.

for…in…


const benzCarObj = {
    
    
        	"brand": "Benz",
            "name": "Benz E300L",
            "price": 550000
        }
// 方式1: for...in...
    for (let attr in benzCarObj) {
    
    
    	console.log(`for...in遍历下的汽车: ${
      
      attr}=> ${
      
      benzCarObj[attr]}`)
    }

Object.keys(obj)


const benzCarObj = {
    
    
        	"brand": "Benz",
            "name": "Benz E300L",
            "price": 550000
        };
        
// 方式2: Object.keys(obj)
    Object.keys(benzCarObj).forEach(function (attr) {
    
    
		console.log(`Object.keys()遍历下的汽车: ${
      
      attr}=> ${
      
      benzCarObj[attr]}`)
	});
	

Object.getOwnPropertyNames(obj)


const benzCarObj = {
    
    
        	"brand": "Benz",
            "name": "Benz E300L",
            "price": 550000
        };
// 方式3: Object.getOwnPropertyNames(obj)
    Object.getOwnPropertyNames(benzCarObj).forEach(function (attr) {
    
    
		console.log(`Object.getOwnPropertyNames()遍历下的汽车: ${
      
      attr}=> ${
      
      benzCarObj[attr]}`)
    });

Object.getOwnPropertySymbols(obj)


// 方式4: Object.getOwnPropertySymbols(obj)
	let brand = Symbol('brand');
	let name = Symbol('name');
	let price = Symbol('price');
	let bmwCarObj = {
    
    
		[brand]: "BMW",
		[name]: "BMW 530Li",
		[price]: 489800
	};
	let bmwCarObjSymbols = Object.getOwnPropertySymbols(bmwCarObj);
	console.log(bmwCarObjSymbols);
	

Reflect.ownKeys(obj)


const benzCarObj = {
    
    
        	"brand": "Benz",
            "name": "Benz E300L",
            "price": 550000
        };
        
// 方式5: Reflect.ownKeys(obj)
	Reflect.ownKeys(benzCarObj).forEach(function (attr) {
    
    
		console.log(`Reflect.ownKeys()遍历下的汽车: ${
      
      attr}=> ${
      
      benzCarObj[attr]}`)
	});
	

4. Collection - Set

ES6 provides a new data structure Set. It is similar to an array, but the values ​​​​of the members are all unique, and there are no duplicate values. Set itself is a constructor used to generate the Set data structure.

Set.prototype.keys()


let carSet = new Set(["Benz", "BMW", "Lexus"]);
// 方式1:Set.prototype.keys()
    for (let car of carSet.keys()) {
    
    
    	console.log(`Set.prototype.keys()遍历下的集合元素: ${
      
      car}`)
    }


Set.prototype.values()


let carSet = new Set(["Benz", "BMW", "Lexus"]);
// 方式2:Set.prototype.values()
	for (let car of carSet.values()) {
    
    
		console.log(`Set.prototype.values()遍历下的集合元素: ${
      
      car}`)
	}

Set.prototype.entries()


let carSet = new Set(["Benz", "BMW", "Lexus"]);
// 方式3:Set.prototype.entries()
	for (let [index, car] of carSet.entries()) {
    
    
		console.log(`Set.prototype.entries()遍历下的集合元素: ${
      
      index} => ${
      
      car}`)
	}

forEach()


let carSet = new Set(["Benz", "BMW", "Lexus"]);
// 方式4:forEach()
	carSet.forEach((index, car) => {
    
    
		console.log(`forEach()遍历下的集合元素:${
      
      index} => ${
      
      car}`)
    });

5. Mapping - Map

Map data structure. It is similar to an object, and it is also a collection of key-value pairs, but the scope of the "key" is not limited to strings, and various types of values ​​(including objects) can be used as keys. In other words, the Object structure provides a "string-value" correspondence, and the Map structure provides a "value-value" correspondence, which is a more complete implementation of the Hash structure. If you need a "key-value pair" data structure, Map is more suitable than Object.

Map.prototype.keys()


const carMap = new Map([
		['name', 'BMW 530Li'],
		['price',  498520],
	]);
// 方式1:Map.prototype.keys()
    for (let attr of carMap.keys()) {
    
    
    	console.log(`Map.prototype.keys()遍历下的集合元素: ${
      
      attr}`)
    }


Map.prototype.values()


const carMap = new Map([
		['name', 'BMW 530Li'],
		['price',  498520],
	]);

// 方式2:Map.prototype.values()
	for (let attr of carMap.values()) {
    
    
		console.log(`Map.prototype.values()遍历下的集合元素: ${
      
      attr}`)
	}

Map.prototype.entries()


const carMap = new Map([
		['name', 'BMW 530Li'],
		['price',  498520],
	]);

// 方式3:Map.prototype.entries()
	for (let [attr, value] of carMap.entries()) {
    
    
		console.log(`Map.prototype.entries()遍历下的集合元素: ${
      
      attr} => ${
      
      attr}`)
	}

forEach()


const carMap = new Map([
		['name', 'BMW 530Li'],
		['price',  498520],
	]);

// 方式4:forEach()
	carMap.forEach((index, car) => {
    
    
		console.log(`forEach()遍历下的集合元素:${
      
      index} => ${
      
      car}`)
    });

6 Summary

6.1 The break and continue problem

  • In the forEach, map, filter, reduce, every, some functions, the break and continue keywords will not take effect, because they are in the function, but the function solves the problem of the closure trap.
  • To use break and continue, you can use for, for...in, for...of, while.

6.2 Recommendations for use

  • Traversing an array: for(), forEach(), map(), for...of.
  • Traversing objects: for...in...

Reference document:
Ruan Yifeng's document https://es6.ruanyifeng.com/#docs/iterator

Guess you like

Origin blog.csdn.net/oschina_41731918/article/details/128462396