JS 访问对象的属性,你知道有哪些方法?

相信对象对于每个使用JavaScript的人来说都不陌生。访问对象的属性几乎日常开发每天都在用。下面我们一起探索下有哪些方式可以实现属性的访问。

访问对象属性介绍

对象是JavaScript的一种常见的数据类型。它允许我们以键值对的形式存储数据。这一系列的键成为对象的属性。

常见的访问对象的属性的方式有三种,包括点号、方括号和对象分解。点号也经常被叫做点号属性访问器。而方括号表示法也被称为方括号属性访问器。

这三种访问方式都是在你知道属性名的情况下,否则于事无补。你只能通过循环遍历获取所有的属性,其中包括你想要获取的那个属性。下面来分别看下三种访问方式。

点号

点号访问器是访问属性里用的最多的一种方式。或许是最简单的一种形式。语法就是你先指定一些对象,然后根据你所知道的属性名,在对象和属性名之间用点号连接。

使用同样的方式你也可以访问对象里更深层次的属性。通过层层嵌套的方式将它们连接起来。例如obj.shallowProp.deeperProp.DeepestProp

// Create an object using object literal:
const myObj = {
  name: 'Anthony Edward Stark',
  alias: 'Iron Man',
  gender: 'male',
  education: 'MIT',
  affiliation: {
    current: 'Avengers'
  },
  creators: ['Stan Lee', 'Larry Lieber', 'Don Heck', 'Jack Kirby'],
  status: {
    alignment: 'good'
  }
}

// Accessing object properties with dot notation:
// First: name of the object.
// Second: name of the property to access.
// Third: dot character between the object and property.
console.log(myObj.name)
// Output:
// 'Anthony Edward Stark'

// Accessing deeper object properties:
// Access the "current" property that exists
// in nested object assigned to "affiliation" property
console.log(myObj.affiliation.current)
// Output:
// 'Avengers'

在JavaScript中,有规则说明什么是有效标识符和无效标识符。有效标识符包含Unicode字母、$、_和数字0-9。但是不能以数字开头。当我们在声明变量的时候要注意这些规则。

在使用点访问器也要注意属性名的有效性。点访问器只在有效的标识符的情况下访问才有结果。如果该属性名以数字开头或者只包含数字,再或者包含-符号,就不能使用点访问器。

这个时候我们就得使用方括号访问器了。

// Create an object:
myObj = {
  1: 'First property',
  'first-name': 'Bruce',
}

// Try to use dot notation
// to access properties on "myObj".
console.log(myObj.1)
// Output:
// SyntaxError: Unexpected token

console.log(myObj.first-name)
// Output:
// NaN

// Try to use bracket notation
// to access properties on "myObj".
console.log(myObj['1'])
// Output:
// 'First property'

console.log(myObj[1])
// Output:
// 'First property'

console.log(myObj['first-name'])
// Output:
// 'Bruce'

方括号

第二种访问对象属性的方式就是方括号表示法。顾名思义就是通过方括号去访问,和点号有点类似。但是又有很大的区别。

首先我们给属性名加上引号,单引号或者双引号都可以。然后给它们整体用方括号包起来放在对象的后面。

方括号访问器也支持一级以上的属性访问。和点号类似。如果遇到属性值为数组的情况,则通过方括号加索引值得方式来获取该变量。

// Create an object:
const myObj = {
  name: 'Bruce Thomas Wayne',
  alias: 'Batman',
  affiliation: ['Batman Family', 'Justice League', 'Outsiders', 'Guild of Detection'],
  status: {
    alignment: 'good',
    occupation: 'businessman'
  }
}

// Accessing object properties with bracket notation:
// First: name of the object.
// Second: name of the property to access.
// Note: property name must be wrapped with quotes
// and then with square brackets.
console.log(myObj['name'])
// Output:
// 'Bruce Thomas Wayne'

// Accessing deeper object properties:
// Access the "alignment" property that exists
// in nested object assigned to "status" property
console.log(myObj['status']['alignment'])
// Output:
// 'good'

// Accessing array items in objects:
// Access the second item inside the array
// assigned to "affiliation" property.
console.log(myObj['affiliation'][1])
// Output:
// 'Justice League'

有趣的一点是方括号支持通过计算的属性名进行访问。简而言之就是你一开始可能并不知道该属性名,但是之后这个属性名被存在某一个变量中,你可以引用此变量来访问与变量值匹配的属性。

注意区别在于,变量名放在方括号里是不需要加引号的。

// Create an object:
const myObj = {
  name: 'James Howlett',
  alias: 'Wolverine',
  status: {
    alignment: 'good'
  }
}

// Assign a property you want to access to a variable:
const myProp = 'alias'

// Use the variable to access specific property ("alias"):
// Referencing "myProp" will return value "alias",
// which will be used to access the same property ("alias").
// I.e.: myObj[myProp] => myObj['alias']
console.log(myObj[myProp])
// Output:
// 'Wolverine'

对象分解法

最后一种访问对象属性的方式就是对象分解法。可能很少有人用到。作为ES6规范的一部分,解构最近被加到JavaScript中来。由于它的简单易用,受到广大开发者的喜爱。

经常在声明变量的时候用到。在赋值运算的左边使用大括号包起属性的名称,右边即为对象。通过这种方式将指定的属性的值来给变量赋值。

// Create an object:
const myObj = {
  name: 'Unknown',
  alias: 'The Joker',
  affiliation: ['Black Glove', 'Injustice Gang', 'Injustice League', 'Joker League of Anarchy', 'Justice League of Arkham'],
  status: {
    alignment: 'bad',
    occupation: 'criminal'
  }
}

// Extract the value of "alias" property:
const { alias } = myObj

// Log the value of new "alias" variable:
console.log(alias)
// Output:
// 'The Joker'

还可以同时给多个属性解构,属性名称之间通过逗号隔开。

// Create an object:
const myObj = {
  name: 'Dr. Reed Richards',
  alias: 'Mister Fantastic',
  affiliation: 'Fantastic Four',
  status: {
    alignment: 'good'
  }
}


// Use object destructuring to assign multiple variables:
// Desctructure "name", "alias", "affiliation" and "status".
const { name, alias, affiliation, status } = myObj

// Log the values of new variables:
console.log(name)
// Output:
// 'Dr. Reed Richards'

console.log(alias)
// Output:
// 'Mister Fantastic'

console.log(affiliation)
// Output:
// 'Fantastic Four'

console.log(status)
// Output:
// { alignment: 'good' }

使用解构的方式为变量赋值变得如此简单。但是如果你想给一个变量名不属性名相同的变量赋值,怎么办?也是可以的,对象解构允许你给变量指定别名。这样你就可以通过别名引用这个变量。

使用方式就是在左侧的属性名的后面通过:隔开。

// Create an object:
const myObj = {
  name: 'Bruce Banner',
  alias: 'Hulk',
  affiliation: ['S.H.I.E.L.D.'],
  status: {
    alignment: 'good'
  }
}

// Extract the value of "name" property
// and assign it to variable called "realName" (new alias).
const { name: realName } = myObj

// Use new alias "realName" to get the value
console.log(realName)
// Output:
// 'Bruce Banner'

如果你想从对象解构的属性中同时改变多个变量名,方法类似。只要在每个属性名的后面增加新的变量名,然后用:隔开即可。

// Create an object:
const myObj = {
  name: 'Oliver Jonas Queen',
  alias: 'Green Arrow',
  affiliation: ['Justice League', 'Justice Society International'],
  status: {
    alignment: 'good'
  }
}

// Change multiple variable names:
// Change variable for "name" to "realName".
// Change variable for "alias" to "heroName".
// Change variable for "affiliation" to "connection".
const { name: realName, alias: heroName, affiliation: connection } = myObj

// Log all values using new variable names:
console.log(realName)
// Output:
// 'Oliver Jonas Queen'

console.log(heroName)
// Output:
// 'Green Arrow'

console.log(connection)
// Output:
// [ 'Justice League', 'Justice Society International' ]

对象解构使用起来很爽吧,但是如果你访问的属性不存在会怎么样?有一种方式你可以做的是提供一个默认值。在属性名不存在的时候,获取的就是默认值。

我们将默认值通过=加到属性名的后面,如果这个时候又为属性名增加别名,那么就加在别名的后面。

// Create an object:
const myObj = {
  name: 'Richard John Grayson',
  alias: 'Nightwing',
  status: {
    alignment: 'good'
  }
}

// Deconstruct the "name" property
// and add default value in case it doesn't exist.
const { name = 'Anonymous' } = myObj

// Log the value of name
console.log(name)
// Output:
// 'Richard John Grayson'

// Deconstruct the "name" property
// and "affiliation" property,
// change it to "connections" and add default value
// in case "affiliation" property doesn't exist.
const { name, affiliation: connections = 'No connections' } = myObj

// Log the value of new variable "connections":
console.log(connections)
// Output:
// 'No connections'

解构的时候遇到计算属性怎么办?

和方括号访问器类似,对象解构也支持属性是一个变量的情况。除了使用方括号将属性名包起来以外,值得一提的是,这个时候你必须要为它指定一个别名,否则会出现语法错误。

// Create an object:
const myObj = {
  name: 'Max Eisenhardt',
  alias: 'Magneto',
  status: {
    alignment: 'bad'
  },
  creators: ['Stan Lee', 'Jack Kirby']
}

// Assign a property you want to access to a variable:
const myProp = 'name'

// Use the variable to access specific property ("name")
// and also create alias for it:
// Referencing "myProp" will now return value "name",
// which will be used to access the "name" property.
const { [myProp]: name } = myObj

// Log the value of new variable "name":
console.log(name)
// Output:
// 'Wolverine'

// Use computed property name with default value:
const myProp = 'powers'

// Use the variable to access specific property ("powers")
// and create alias "abilities" for it.
// If the property doesn't exist, use 'Unknown'
// as the default value for the new variable.
const { [myProp]: abilities = 'Unknown' } = myObj

// Log the value of new variable "abilities":
console.log(abilities)
// Output:
// 'Unknown'

结论:以上三种访问对象属性的方式:点号和方括号和对象分解的方式。具体采用哪种,我们平时使用的时候根据具体情况而定,并没有什么好坏之分。尤其要注意每种使用方式的边缘情况,以上都有说到。

评论

这篇文章目前有 2 条评论

编程范儿进行回复 取消回复

电子邮件地址不会被公开。 必填项已用*标注

Sidebar