当前位置:网站首页>Js - 内置对象
Js - 内置对象
2022-07-30 11:31:00 【sgling】
Object.assgin()方法:
**
Object.assgin()==> 方法用于将所有可枚举属性的值从一个或多个源对象分配到目标对象。它将返回目标对象。
JavaScript Demo: Object.assign()
const target = { a: 1, b: 2 };
const source = { b: 4, c: 5 };
const returnedTarget = Object.assign(target, source);
console.log(source);
// expected output: Object { b: 4, c: 5 }
console.log(target);
// expected output: Object { a: 1, b: 4, c: 5 }
console.log(returnedTarget);
// expected output: Object { a: 1, b: 4, c: 5 }
语法:
Object.assign(target, ...sources);
参数:
target: 目标对象 sources: 源对象
返回值:
target: 目标对象
描述:
**
如果目标对象中的属性具有相同的键,则属性将被源对象中的属性覆盖。后面的源对象的属性将类似地覆盖前面的源对象的属性。 Object.assign 方法只会拷贝源对象自身的并且可枚举的属性到目标对象。该方法使用源对象的[[Get]]和目标对象的[[Set]],所以它会调用相关 getter 和 setter。因此,它分配属性,而不仅仅是复制或定义新的属性。如果合并源包含getter,这可能使其不适合将新属性合并到原型中。为了将属性定义(包括其可枚举性)复制到原型,应使用Object.getOwnPropertyDescriptor()和Object.defineProperty() 。 String类型和 Symbol 类型的属性都会被拷贝。 在出现错误的情况下,例如,如果属性不可写,会引发TypeError,如果在引发错误之前添加了任何属性,则可以更改target对象。
备注: 「Object.assign 不会在那些source对象值为 null 或 undefined 的时候抛出错误。」
示例:
复制一个对象
const obj = { a: 1 };
const copy = Object.assign({}, obj);
console.log(copy); // { a: 1 }
合并对象:
const o1 = { a: 1 };
const o2 = { b: 2 };
const o3 = { c: 3 };
const obj = Object.assign(o1, o2, o3);
console.log(obj); // { a: 1, b: 2, c: 3 }
console.log(o1); // { a: 1, b: 2, c: 3 }, 注意目标对象自身也会改变。
合并具有相同属性的对象:
const o1 = { a: 1, b: 2, c: 3 };
const o2 = { a: 1, b: 2 };
const o3 = { c: 3 };
const obj = Object.assign({}, o1, o2, o3);
console.log(obj); // { a: 1, b: 2, c: 3 }
边栏推荐
- 云原生应用的概念和云原生应用的 15 个特征
- 久经沙场的程序员居然也被某鱼的假程序员骗了,程序员之间的信任应该是最高的,他一个人毁了这种信任感
- Explain the problem of change exchange in simple terms - the shell of the backpack problem
- 超图iServer rest服务之最佳路径分析
- LinkedList与链表
- MySQL——数据库基础
- 基于MySQL数据库,Redis缓存,MQ消息中间件,ES搜索引擎的高可用方案解析
- decodeURIComponent(), eval(), encodeURIComponent()
- win下怎么搭建php环境的方法教程
- [Database basics] redis usage summary
猜你喜欢

Manage reading notes upward

Reverse linked list - recursive inversion method

High energy output!Tencent's internal MyCat middleware manual, both theoretical and practical

物联网技术概论:第6章

SCM engineers written questions induction summary

LeetCode_235_Last Common Ancestor of Binary Search Tree

概率论的学习和整理7:理解期望和方差还是要回到随机试验本身,期望不是平均值,方差的公式不同情况不同

云原生应用的概念和云原生应用的 15 个特征

概率论的学习整理--番外2:和二项式,组合相关的杨辉三角

Performance testing of API Gateway APISIX on Google Cloud T2A and T2D
随机推荐
[ASP.NET Core] Dependency Injection for Option Classes
流水线上的农民:我在工厂种蔬菜
Leetcode 125. 验证回文串
【ASP.NET Core】选项类的依赖注入
MySQL——数据库基础
TensorFlow custom training function
反转链表-迭代反转法
IO/多路复用(select/poll/epoll)
自定义查询--关于倒排索引的研究
【JZ64 求1+2+3+...+n】
【32. 图中的层次(图的广度优先遍历)】
External Force Estimation Based on Time Delay Estimation with Perturbed Kalman Filter
文本的对齐方式、行高、空间 等总结
Based on the analysis of the acoustic channel cable tunnel positioning technology
Verilog语法基础HDL Bits训练 08
Difference between C# enumeration type and xaml
【数据库基础】redis使用总结
EA中的业务对象和业务实体你分得清吗?
Matlab基础(5)——符号运算
UE5 GAS 学习笔记 后记0