Home >Web Front-end >JS Tutorial >Write a JavaScript program to list the properties of a JavaScript object
In the previous article "Quickly find the area of a triangle using js" I introduced you how to use JavaScript to find the area of a triangle. Friends who are interested can take a look ~ Today this article will introduce it to you How to write a JavaScript program to list the properties of a JavaScript object.
Let’s give you a detailed introduction to the method of listing the properties of a JavaScript object:
First create an HTML sample file;
Then directly enter the code:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title></title> </head> <body> <script> function _keys(obj) { if (!isObject(obj)) return []; if (Object.keys) return Object.keys(obj); var keys = []; for (var key in obj) if (_.has(obj, key)) keys.push(key); return keys; } function isObject(obj) { var type = typeof obj; return type === 'function' || type === 'object' && !!obj; } console.log(_keys({red: "#FF0000", green: "#00FF00", white: "#FFFFFF"})); </script> </body> </html>
The results are as follows:
["red","green","white"]
In the above code, you need to understand the function methods:
1. The Object.keys() method will Returns an array consisting of the self-enumerable properties of a given object. The order of the property names in the array is consistent with the order returned when the object is traversed normally; the syntax is "Object.keys(obj)
", the parameter obj represents the object whose enumerated properties are to be returned; the return value is a string array representing all enumerable properties of the given object.
2. The push() method can add one or more elements to the end of the array and return the new length; the syntax is "arrayObject.push(newelement1,newelement2,....,newelementX )
"; The return value is the new length after adding the specified value to the array.
The parameters are expressed as follows:
newelement1,要添加到数组的第一个元素。 newelement2,要添加到数组的第二个元素。 newelementX,可添加多个元素。
push() method can add its parameters to the end of arrayObject in order. It directly modifies the arrayObject instead of creating a new array. The push() method and pop() method use the first-in-last-pop function provided by the array.
Note: JavaScript can "display" data by writing console.log() to the browser console.
Finally, I would like to recommend "JavaScript Basic Tutorial"~ Welcome everyone to learn~
The above is the detailed content of Write a JavaScript program to list the properties of a JavaScript object. For more information, please follow other related articles on the PHP Chinese website!