×

来聊聊JavaScript中一些常用的对象方法

作者:Terry2019.08.06来源:Web前端之家浏览:7400评论:0
关键词:js对象方法

500.jpg

来聊聊JavaScript中一些常用的对象方法,JavaScript中的对象是键/值(key/value)对的集合。值可以包含属性和方法,并且可以包含所有其他JavaScript数据类型,例如字符串,数字和布尔值。

JavaScript中的所有对象都来自父对象构造函数。对象有许多有用的内置方法,我们可以使用和访问这些方法来简化处理单个对象的工作。与数组实例上使用的sort()和reverse()等数组原型方法不同,对象方法直接用于对象构造函数,并将对象实例用作参数。这就是所谓的静态方法。

Object.create()

Object.create()用于创建一个新对象并链接现有对象的原型。

我们可以创建一个job对象实例,并将其扩展到更特定的对象。

// Initialize an object with properties and methods
const job = {
  position: 'cashier',
  type: 'hourly',
  isAvailable: true,
  showDetails() {
    const accepting = this.isAvailable
      ? 'is accepting applications'
      : 'is not currently accepting applications'

    console.log(`The ${this.position} position is ${this.type} and ${accepting}.`)
  },
}

// Use Object.create to pass properties
const barista = Object.create(job)

barista.position = 'barista'
barista.showDetails()

输出:

The barista position is hourly and is accepting applications.

barista对象现在有一个属性—position,但是job中的所有其他属性和方法都可以通过原型获得。Object.create()有助于通过最小化重复来保持代码的干爽。

Object.keys()

Object.keys()创建一个包含对象键的数组。

我们可以创建一个对象并打印键数组。

// Initialize an object
const employees = {
  boss: 'Michael',
  secretary: 'Pam',
  sales: 'Jim',
  accountant: 'Oscar',
}
// Get the keys of the object
const keys = Object.keys(employees)
console.log(keys)

输出:

["boss", "secretary", "sales", "accountant"]

Object.keys 可用于迭代对象的键和值。

// Iterate through the keys
Object.keys(employees).forEach(key => {
  let value = employees[key]

  console.log(`${key}: ${value}`)
})

输出:

boss: Michael
secretary: Pam
sales: Jim
accountant: Oscar

Object.keys 对于检查对象的长度也很有用。

// Get the length of the keys
const length = Object.keys(employees).length

console.log(length)

输出:

4

使用length属性,我们可以计算employee的4个属性。

Object.values()

Object.values()创建一个包含对象值的数组。

// Initialize an object
const session = {
  id: 1,
  time: `26-July-2018`,
  device: 'mobile',
  browser: 'Chrome',
}
// Get all values of the object
const values = Object.values(session)
console.log(values)

输出:

[1, "26-July-2018", "mobile", "Chrome"]

Object.keys()和Object.values()是从对象返回数据的简单直接的方法。

Object.entries()

Object.entries()创建一个对象的键/值对的嵌套数组。

// Initialize an object
const operatingSystem = {
  name: 'Ubuntu',
  version: 18.04,
  license: 'Open Source',
}
// Get the object key/value pairs
const entries = Object.entries(operatingSystem)
console.log(entries)

输出:

[
    ["name", "Ubuntu"]
    ["version", 18.04]
    ["license", "Open Source"]
]

一旦我们有了键/值对数组,我们就可以轻松地使用该forEach()方法循环并处理结果。

const entries = Object.entries(operatingSystem)
// Loop through the results
entries.forEach(entry => {
  let key = entry[0]
  let value = entry[1]
  console.log(`${key}: ${value}`)
})

输出:

name: Ubuntu
version: 18.04
license: Open Source

Object.entries()方法方法将只返回对象实例本身的属性,而不返回可能通过其原型继承的任何属性。

Object.assign()

Object.assign()用于将值从一个对象复制到另一个对象。

我们可以创建两个对象,并将它们与'Object.assign()'合并

// Initialize an object
const name = {
  firstName: 'Philip',
  lastName: 'Fry',
}
// Initialize another object
const details = {
  job: 'Delivery Boy',
  employer: 'Planet Express',
}
// Merge the objects
const character = Object.assign(name, details)
console.log(character)

输出:

{firstName: "Philip", lastName: "Fry", job: "Delivery Boy", employer: "Planet Express"}

也可以使用spread运算符(...)来完成相同的任务。

// Merge the object with the spread operator
const character = { ...name, ...details }
console.log(character)

输出:

{firstName: "Philip", lastName: "Fry", job: "Delivery Boy", employer: "Planet Express"}

对象文字中的这种扩展语法也称为浅层克隆。

Object.freeze()

Object.freeze()可防止修改对象的属性和值,并防止在对象中添加或删除属性。

// Initialize an object
const user = {
  username: 'AzureDiamond',
  password: 'hunter2',
}
// Freeze the object
const newUser = Object.freeze(user)
newUser.password = '*******'
newUser.active = true
console.log(newUser)

输出:

{username: "AzureDiamond", password: "hunter2"}

在本例中,我们试图用******重写密码 hunter2,但是password属性保持不变。我们还尝试添加一个新属性active,但是没有添加。

isfrozen()可用来确定对象是否被冻结,并返回一个布尔值。

Object.seal()

Object.seal()可防止将新属性添加到对象,但允许修改现有属性。这种方法类似于Object.freeze()。

// Initialize an object
const user = {
  username: 'AzureDiamond',
  password: 'hunter2',
}
// Seal the object
const newUser = Object.seal(user)
newUser.password = '*******'
newUser.active = true
console.log(newUser)

输出:

{username: "AzureDiamond", password: "*******"}

新属性active未添加到密封对象,但password属性已成功更改。

Object.getPrototypeOf()

Object.getPrototypeOf()用于获取[[Prototype]]对象的内部隐藏,也可通过__proto__属性访问。

在这个例子中,我们可以创建一个可以访问Array原型的数组。

const employees = ['Ron', 'April', 'Andy', 'Leslie']
Object.getPrototypeOf(employees)

输出:

[constructor: ?, concat: ?, find: ?, findIndex: ?, pop: ?, …]

我们可以在该原型输出中看到employees数组访问pop,find以及其他数组原型方法。我们可以通过测试employees原型来证实这一点Array.prototype。

Object.getPrototypeOf(employees) === Array.prototype;

输出:

true

此方法可用于获取有关对象的更多信息或确保它可以访问另一个对象的原型。还有一种相关Object.setPrototypeOf()方法将一个原型添加到另一个对象。建议您使用,Object.create()因为它更快,性能更高。

总结

对象有许多有用的方法可以帮助我们修改,保护和迭代它们。在本教程中,我们回顾了如何创建和分配新对象,迭代对象的键和/或值,以及冻结或密封对象。

您的支持是我们创作的动力!
温馨提示:本文作者系Terry ,经Web前端之家编辑修改或补充,转载请注明出处和本文链接:
https://www.jiangweishan.com/article/js238420983ujusdflj.html

网友评论文明上网理性发言 已有0人参与

发表评论: