js给对象添加属性
在 JavaScript 中,可以使用以下几种方法给对象添加属性:
方法一:使用点表示法
| const object = {}; |
| object.propertyName = propertyValue; |
复制
方法二:使用方括号表示法
| const object = {}; |
| object['propertyName'] = propertyValue; |
复制
方法三:使用 Object.defineProperty() 方法
| const object = {}; |
| Object.defineProperty(object, 'propertyName', { |
| value: propertyValue, |
| writable: true, |
| enumerable: true, |
| configurable: true |
| }); |
复制
方法四:使用 Object.defineProperties() 方法一次性添加多个属性
| const object = {}; |
| Object.defineProperties(object, { |
| propertyName1: { value: propertyValue1 }, |
| propertyName2: { value: propertyValue2 }, |
| |
| }); |
复制
以上是几种常见的方法,可以根据具体需求选择适合的方式给对象添加属性。