首页 > web前端 > js教程 > 正文

JavaScript 中的对象是什么?

霞舞
发布: 2024-12-06 20:42:02
转载
636人浏览过

javascript 中的对象是什么?

  • 定义: 对象存储带键的数据集合和更复杂的实体。
  • 创作:
    • 对象构造函数语法: 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"
登录后复制

测试和迭代属性

  1. 属性存在:
    • 在 obj 中使用“key”来检查某个键是否存在。
   let user = { age: undefined }
   alert('age' in user) // true
登录后复制
  1. 使用 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]}`)
}
登录后复制

现实示例:产品库存

以下是如何在实际场景中使用对象,例如管理产品库存:

WeShop唯象
WeShop唯象

WeShop唯象是国内首款AI商拍工具,专注电商产品图片的智能生成。

WeShop唯象 113
查看详情 WeShop唯象
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 迭代键。
  • 了解整数与非整数属性排序。

以上就是JavaScript 中的对象是什么?的详细内容,更多请关注php中文网其它相关文章!

最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
来源:dev.to网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号