In JavaScript, even if you don't know the specific key names of an object, you can obtain all property values through various methods.
Method One: Using Object.values()
This is the most straightforward method to retrieve all property values of an object. The Object.values() function returns an array containing all enumerable property values of the input object. This method does not include inherited property values.
Example Code:
javascriptconst person = { name: "张三", age: 30, occupation: "程序员" }; const values = Object.values(person); console.log(values); // Output: ['张三', 30, '程序员']
Method Two: Using for...in Loop
Although the for...in loop is primarily used to iterate over object key names, it can also be used to retrieve corresponding property values within the loop. Unlike Object.values(), this method can also access enumerable properties on the object's prototype chain.
Example Code:
javascriptconst person = { name: "李四", age: 28, occupation: "设计师" }; const values = []; for (let key in person) { if (person.hasOwnProperty(key)) { // Check to ensure that the property is a direct property of the object, not inherited values.push(person[key]); } } console.log(values); // Output: ['李四', 28, '设计师']
Method Three: Using Object.keys() Combined with Array's map() Method
First, use Object.keys() to retrieve all key names, then use the array's map() method to map each key name to its corresponding property value.
Example Code:
javascriptconst person = { name: "王五", age: 35, occupation: "医生" }; const keys = Object.keys(person); const values = keys.map(key => person[key]); console.log(values); // Output: ['王五', 35, '医生']
Each method has its own advantages, and you can select the most appropriate one based on specific requirements and context to retrieve object property values.