let user = { name: 'John', age: 30, }
user.isAdmin = true // Adding delete user.age // Removing
user['likes birds'] = true alert(user['likes birds']) // true
let fruit = 'apple' let bag = { [fruit]: 5 } // Equivalent to { "apple": 5 }
function makeUser(name, age) { return { name, age } // Same as name: name, age: age }
let obj = { 0: 'test' } alert(obj[0]) // "test"
let user = { age: undefined } alert('age' in user) // true
let user = { name: 'John', age: 30 } for (let key in user) { alert(key) // Outputs: "name", "age" alert(user[key]) // Outputs: "John", 30 }
let userProfile = { firstName: 'Jane', lastName: 'Smith', email: 'jane.smith@example.com', isVerified: true, address: { street: '123 Elm Street', city: 'Metropolis', postalCode: '12345', }, interests: ['reading', 'hiking', 'coding'], // Method inside an object getFullName() { return `${this.firstName} ${this.lastName}` }, // Dynamically updating properties updateEmail(newEmail) { this.email = newEmail console.log(`Email updated to ${this.email}`) }, } // Accessing properties console.log(userProfile.getFullName()) // Output: Jane Smith // Updating email using the method userProfile.updateEmail('jane.doe@example.com') // Output: Email updated to jane.doe@example.com // Accessing nested properties console.log(userProfile.address.city) // Output: Metropolis // Iterating over interests console.log('User Interests:') userProfile.interests.forEach((interest) => console.log(interest))
建立物件後可以動態新增或刪除屬性。
// Adding a new property userProfile.phoneNumber = '555-1234' console.log(userProfile.phoneNumber) // Output: 555-1234 // Deleting a property delete userProfile.isVerified console.log(userProfile.isVerified) // Output: undefined
建立物件時,可以使用方括號動態計算屬性名稱。
let key = 'favoriteColor' let userPreferences = { [key]: 'blue', [key + 'Secondary']: 'green', } console.log(userPreferences.favoriteColor) // Output: blue console.log(userPreferences.favoriteColorSecondary) // Output: green
使用 for...in,可以迴圈遍歷物件中的所有鍵。
for (let key in userProfile) { console.log(`${key}: ${userProfile[key]}`) }
以下是如何在實際場景中使用對象,例如管理產品庫存:
let user = { name: 'John', age: 30, }
in 運算子檢查物件中是否存在屬性。它在驗證可選或動態添加的屬性時特別有用。
user.isAdmin = true // Adding delete user.age // Removing
物件是 JavaScript 的核心,提供彈性與功能:
以上是JavaScript 中的物件是什麼?的詳細內容。更多資訊請關注PHP中文網其他相關文章!