JavaScript 中的对象是什么?

风之吻 网站开发 354

JavaScript 中的对象是什么?-第1张图片-风享汇

  定义: 对象存储带键的数据集合和更复杂的实体。

  创作:

  对象构造函数语法: let user = new object();

  对象文字语法: let user = {}; (首选并广泛使用)。


  文字和属性

  对象是属性的集合。属性是一个键:值对。

let user = {
    name: 'john',
    age: 30,
  }

  访问属性:

  点表示法:user.name 返回“john”。

  方括号表示法:user["name"] 也返回“john”。

  添加/删除属性:

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"

  测试和迭代属性

  属性存在:

  在 obj 中使用“key”来检查某个键是否存在。

let user = { age: undefined }
alert('age' in user) // true

  使用 for..in 进行迭代:

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 的核心,提供灵活性和功能:

  键可以是字符串或符号。

  使用点或括号表示法访问属性。

  使用 for..in 迭代键。

  了解整数与非整数属性排序。

标签: JS

发布评论 0条评论)

还木有评论哦,快来抢沙发吧~