| 
                         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()                         (编辑:91站长网) 
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! 
                     |