js中,当对象key存在时,赋最新的value,不存在则创建
时间: 2023-02-08 19:45:17 浏览: 187
在 JavaScript 中,可以使用 `obj[key] = value` 的方式来为对象赋值,如果对象中已经存在该键,则会覆盖原来的值;如果不存在该键,则会新增一个键值对。
例如:
```
let obj = {};
obj["name"] = "John Doe";
console.log(obj); // Output: { name: 'John Doe' }
obj["name"] = "Jane Doe";
console.log(obj); // Output: { name: 'Jane Doe' }
```
或者使用 `Object.assign` 方法
```
let obj = {};
Object.assign(obj, { name: 'John Doe' });
console.log(obj); // Output: { name: 'John Doe' }
Object.assign(obj, { name: 'Jane Doe' });
console.log(obj); // Output: { name: 'Jane Doe' }
```
或者使用 `Object.defineProperty` 方法
```
let obj = {};
Object.defineProperty(obj, 'name', {
value: 'John Doe',
writable: true,
enumerable: true,
configurable: true
});
console.log(obj); // Output: { name: 'John Doe' }
obj.name = 'Jane Doe';
console.log(obj); // Output: { name: 'Jane Doe' }
```
以上方式都可以实现对象key存在时,赋最新的value,不存在则创建。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)