1.ES6
允许对象的属性直接写变量,这时候属性名
是变量名
,属性值
是变量值
。
const age = 12;
const name = "Amy";
const person = {name,age};
console.log(person);
//等同于
const ps ={
name:name,
age:age
}
console.log(ps);
const age = 12;
const name = "Amy";
const person = {
name,
age,
sayHi(){
console.log("Hi");}
};
person.sayHi();
//等同于
const ps ={
name:name,
age:age,
sayHi:function(){
console.log("Hi");
}
}
ps.sayHi();
const obj = {
* myGenerator() {
yield 'hello world';
}
};
//等同于
const obj = {
myGenerator: function* () {
yield 'hello world';
}
};
4.ES6
允许用表达式作为属性名,但是一定要将表达式放在方括号内。
const person = {
["say"+"Hi"](){
console.log("Hi");}
};
person.sayHi();
拓展运算符...
用于取出参数对象所有可遍历属性然后拷贝到当前对象。
let person = {name: "Amy", age: 15};
let someone = { ...person };
console.log(someone);
let age = {age: 15};
let name = {name: "Amy"};
let person = {...age, ...name};
console.log(person);
1.自定义的属性
和拓展运算符对象里面属性
的相同的时候,谁在前面谁被覆盖!!!
let person = {name: "Amy", age: 15};
let someone = { ...person, name: "Mike", age: 17};
console.log(someone); //{name: "Mike", age: 17}
let someone1 = { name: "Mike", age: 17,...person};
console.log(someone1); //{name: "Amy", age: 15}
2.拓展运算符后面是空对象
、null
或者undefined
,没有任何效果也不会报错。
let person = {name: "Amy", age: 15};
let someone = { ...{}, name: "Mike", age: 17};
console.log(someone); //{name: "Mike", age: 17}
let someone1 = { name: "Mike", age: 17,...{}};
console.log(someone1);
1.定义
:用于将源对象
的所有可枚举属性 复制
到目标对象
中。
2.使用
let target = {a: 1};
let object2 = {b: 2};
let object3 = {c: 3};
// 第一个参数是目标对象,后面的参数是源对象
Object.assign(target,object2,object3); // {a: 1, b: 2, c: 3}
console.log(target);
注意:
(1)如果目标对象
和源对象
有同名属性,则后面的属性会覆盖前面的属性。
let target = {a: 1,b:99};
let object2 = {b: 2};
let object3 = {b:88,c: 3};
Object.assign(target,object2,object3); // {a: 1, b: 2, c: 3}
console.log(target);
let obj = {a: 1,b:99};
console.log(Object.assign(obj));
console.log(typeof Object.assign(3));
(3)因为 null 和 undefined 不能转化为对象,所以会报错。
console.log(Object.assign(null)); //Uncaught TypeError: Cannot convert undefined or null to object
console.log(Object.assign(undefined)); //Uncaught TypeError: Cannot convert undefined or null to object
console.log(Object.assign(undefined,{a: 1})); //Uncaught TypeError: Cannot convert undefined or null to object
(4)当参数不止一个时,null 和 undefined 不放第一个,即不为目标对象时,会跳过 null 和 undefined ,不报错。
Object.assign(1,undefined); // Number {1}
Object.assign({a: 1},null); // {a: 1}
(5)assign 的属性拷贝是浅拷贝
let sourceObj = { a: { b: 1}};
let targetObj = {c: 3};
Object.assign(targetObj, sourceObj);
targetObj.a.b = 2;
console.log(sourceObj.a.b); // 2
(6)会将数组处理成对象。所以先将 [2,3] 转为 {0:2,1:3} ,然后再进行属性复制,所以源对象的 0 号属性覆盖了目标对象的 0。
Object.assign([2,3], [5]); // [5,3]
用来比较两个值是否严格相等,与(===)基本类似。
1.使用
console.log(Object.is("q","q"));
console.log(Object.is('1',1));
console.log(Object.is([1],[1]));
console.log(Object.is({q:1},{q:1}));
//一是+0不等于-0
console.log(Object.is(+0,-0)); //false
console.log(+0 === -0 );//true
//二是NaN等于本身
console.log(Object.is(NaN,NaN)); //true
console.log(NaN === NaN); //false