
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 inventory = {
products: [
{
id: 1,
name: 'laptop',
price: 1200,
stock: 25,
},
{
id: 2,
name: 'smartphone',
price: 800,
stock: 50,
},
{
id: 3,
name: 'tablet',
price: 400,
stock: 30,
},
],
// method to display all products
listproducts() {
console.log('product inventory:')
this.products.foreach((product) => {
console.log(
`${product.name} - $${product.price} (stock: ${product.stock})`
)
})
},
// method to update stock
updatestock(productid, quantity) {
let product = this.products.find((p) => p.id === productid)
if (product) {
product.stock += quantity
console.log(`${product.name} stock updated to ${product.stock}`)
} else {
console.log('product not found!')
}
},
}
// list products
inventory.listproducts()
// update stock
inventory.updatestock(2, -5) // decrease stock for smartphone
inventory.listproducts()
in 运算符检查对象中是否存在属性。它在验证可选或动态添加的属性时特别有用。
if ('phoneNumber' in userProfile) {
console.log('Phone number exists:', userProfile.phoneNumber)
} else {
console.log('Phone number not available.')
}
对象是 javascript 的核心,提供灵活性和功能:
以上就是JavaScript 中的对象是什么?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号