对象简介语法及对象新增

对象简介语法

let name = 'Strive';
let age = 18;
let json ={
   
    name,   //name:name,
    age,     //age:age
            /* showA:function(){ return this.name; } */
    showA(){
   
        return this.name;
    },
    showB(){
   
        return this.age;
    }
};
console.log(json.showA(), json.showB());

对象扩展运算符

let {
   x,y,...z} = {
   x : 1,y : 2,a : 3,b : 3};
console.log(x,y,z);
  • 可用来合并两个对象
let ab = {
    ...a, ...b };
// 等同于
let ab = Object.assign({
   }, a, b);

Object.is()

用法:用来比较两个值是否相同,与===基本一致但是有两处不同(+0不等于-0,NaN等于NaN)
如果下列任何一项成立,则两个值相同:

  • 两个值都是 undefined
  • 两个值都是 null
  • 两个值都是 true 或者都是 false
  • 两个值是由相同个数的字符按照相同的顺序组成的字符串
  • 两个值指向同一个对象
  • 两个值都是数字并且
  • 都是正零 +0
  • 都是负零 -0
  • 都是 NaN
  • 都是除零和 NaN 外的其它同一个数字
Object.is('foo', 'foo');     // true
Object.is(window, window);   // true
 
Object.is('foo', 'bar');     // false
Object.is([], []);           // false
 
var foo = {
    a: 1 };
var bar = {
    a: 1 };
Object.is(foo, foo);         // true
Object.is(foo, bar);         // false
 
Object.is(null, null);       // true
 
// 特例 
Object.is(+0, -0);           // false
Object.is(NaN, 0/0);         // true

Object.assign()

作用:用来合并对象
常见用途:
1.复制一个对象
2.合并参数

let json = {
   a:1};
let json2 = {
   b:2, a:2};
let json3 = {
   c:3};
let obj = Object.assign({
   },json,json2,json3);
console.log(obj);//{a:2,b:2,c:3}

用在数组上

let arr = ['apple','banana','orange'];
let arr2 = Object.assign([], arr);
arr2.push('tomato');
console.log(arr2);//["apple", "banana", "orange", "tomato"]
console.log(arr);//["apple", "banana", "orange"]

keys,values,entries

let {
   keys, values, entries} = Object;

let json = {
   
    a:1,
    b:2,
    c:3
};

for(let key of keys(json)){
   
    console.log(key);//a b c
}

for(let value of values(json)){
   
    console.log(value);//1 2 3
}

for(let item of entries(json)){
   
    console.log(item);//['a':1] ['b':2] ['c':3]
}

for(let [key, val] of entrires(json)){
   
    console.log(key, val);
}