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中文网其他相关文章!