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);
- Output
- [
- ["name", "Ubuntu"]
- ["version", 18.04]
- ["license", "Open Source"]
- ]
一旦我们有了键/值对数组,我们就可以行使该forEach()要领轮回并处理赏罚功效。
- // Loop through the results
- entries.forEach(entry => {
- const [key, value] = entry;
- console.log(`${key}: ${value}`);
- });
- Output
- 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);
- Output
- {firstName: "Philip", lastName: "Fry", job: "Delivery Boy", employer: "Planet Express"}
也可以行使睁开语法(Spread syntax)来完成沟通的使命。在下面的代码中,我们将通过睁开语法归并name和details工具,来声明character工具。
- // Initialize an object
- const name = {
- firstName: 'Philip',
- lastName: 'Fry'
- };
- // Initialize another object
- const details = {
- job: 'Delivery Boy',
- employer: 'Planet Express'
- };
- // Merge the object with the spread operator
- const character = {...name, ...details}
- console.log(character);
- Output
- {firstName: "Philip", lastName: "Fry", job: "Delivery Boy", employer: "Planet Express"}
睁开语法(Spread syntax) 在工具语法中也成为浅层克隆(shallow-cloning)。
Object.freeze() (编辑:湖南网)
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!
|