在 javascript 对象中包含键值对属性,并且迭代对象与数组不同。可以使用 for...in 循环以及 Object.keys()、Object.values() 和 Object.entries() 来迭代对象。让我们看看如何使用每种方法:
1。使用 for...in 方法
const person = { name: 'John', age: 30, occupation: 'Engineer' }; for(let key in persons){ console.log(`${person[key]} : ${key}`) } //output // name: 'John', // age: 30, // occupation: 'Engineer'
2.使用Object.keys():方法
object.keys() 是一个 javascript 方法,它以对象作为参数并返回键数组
const person = { name: 'John', age: 30, occupation: 'Engineer' }; const Object_keys = Object.keys(person); console.log(Object_keys)// [ 'name', 'age', 'occupation']```
我们可以使用 object.keys() 来迭代对象
const person = { name: 'John', age: 30, occupation: 'Engineer' }; const Object_keys = Object.keys(person); //here first i have used Object_keys array which i got from Object.keys(person); for(let i = 0 ; i<Object_keys.length;i++){ console.log(`${Object_keys[i]} : ${person[Object_keys[i]]}`); } //here i have used Object_keys array which i got from Object.keys(person); for(let keys of Object_keys){ console.log(`${keys} : ${person[keys]}`); } // here i have just directly use object.key() method for(let keys of Object.keys(person)){ console.log(`${keys}: ${person[keys]}`); } // all three ways will give same output name : John age : 30 occupation : Engineer
3.使用Object.entries():
Object.entries() 是一个 javascript 方法,它以对象为参数并返回键值对的二维数组
const person = { name: 'John', age: 30, occupation: 'Engineer' }; const Object_keyValue = Object.entries(person); //output // [ [ 'name', 'John' ], [ 'age', 30 ], [ 'occupation', 'Engineer' ] ]
我们可以使用Object.entries()来迭代对象
const person = { name: 'John', age: 30, occupation: 'Engineer' }; for (const [key, value] of Object.entries(person)) { console.log(`${key} : ${value}`); } //output // name: 'John', // age: 30, // occupation: 'Engineer'
4。使用 Object.values():
Object.values() 返回对象自己的可枚举属性值的数组。如果您只对值而不是键感兴趣,这会很有用。
const myObject = { prop1: 'value1', prop2: 'value2', prop3: 'value3' }; const values = Object.values(myObject); for (const value of values) { console.log(value); }
以上是可以在 javascript 中迭代'对象”的详细内容。更多信息请关注PHP中文网其他相关文章!