在 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中文網其他相關文章!