Home  >  Article  >  Web Front-end  >  What are the property enumeration methods in JavaScript?

What are the property enumeration methods in JavaScript?

不言
不言Original
2019-01-15 14:37:093396browse

In this article, let’s take a look at the methods of enumerating attributes. In this article, we will mainly learn how to use the forEach(), map(), and filter() methods. Let’s take a look at the specific content.

What are the property enumeration methods in JavaScript?

We introduced you to the method of Object.keys in What are the property enumeration methods in JavaScript? to obtain object properties in our previous article, let’s take a look next See how to enumerate properties in What are the property enumeration methods in JavaScript?.

Let’s take a look at common object data first

var obj = {
  name: '张 三',  
  age: 30,  
  area: '北京'
}
Enumerate properties through forEach()

forEach() is a method that can be used for arrays, but due to Object.keys The return value of () is an array, so the compatibility is very good.

To enumerate properties, please see the following description.

Object.keys(obj).forEach(function(data) {
  console.log(data);
})

Execution results

name
age
area

Please note that we define the function as a parameter of forEach().

With this description, any function can be executed on each attribute.

By the way, you can also use a format like "obj [data]" to output the value of the attribute!

Enumerating properties through map()

The basic usage is the same as forEach(), but it is a function that obtains properties as an array return value.

Please see the example below!

var result = Object.keys(obj).map(function(data) {
    return data;
})

Execution results

["name", "age", "area"]

Please pay attention to the content of the function specified in the map() parameter.

Enumerate properties through filter()

The usage of filter() and map() is almost the same.

Please see the example below

var result = Object.keys(obj).filter(function(data) {
    return data;
})

Execution results

["name", "age", "area"]

In this example, we just replaced the map() part with filter(), but the execution The result is the same.

The characteristic of filter() is that it can describe the process of obtaining values ​​only when specific conditions are met.

For example, "return data ==='name'" only returns a value if the attribute has "name".

If you use filter(), it would also be easy to extract only users over 30 years old, for example.

The above is the detailed content of What are the property enumeration methods in JavaScript?. 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