1.es6直接写入变量和函数,作为对象的属性和方法
const name = 'hattie',
age = 18;
const person = {
// name: name,
// age: age,
// sayName: function() {
// console.log(this.name);
// }
//以下为es6写法
name,
age,
sayName() {
console.log(this.name);
}
}
person.sayName();
2.将传入的参数封装成对象,并返回
function fn(x, y) {
return {x,y}
}
console.log(fn(1, 2)); //{x: 1, y: 2}
let fn2 = (x, y) => ({x,y});
console.log(fn2(3, 4)); //{x: 3, y: 4}
3.es6在对象中的应用set(){}和get(){},类似java的set和get方法
let car = {
wheel: 4,
setWheel(newWheel) {
if (newWheel < this.wheel) {
throw new Error('请增加轮子个数');
}
this.wheel = newWheel;
},
get() {
return this.wheel;
}
}
console.log(car.get());
car.setWheel(5);
console.log(car.get());
4.对对象变量名扩展 []
const name = 'my';
const obj = {
[name + 'name']: 'hattie',
[name + 'fn']() {
console.log(this);
}
}
console.log(obj); //{myname: "hattie", myfn: ƒ}
5.对象的方法
1.is() 比较 与 ===唯一不同的是NaN
console.log(NaN === NaN); //false
console.log(Object.is(NaN, NaN)); //true
// (method) ObjectConstructor.is(value1: any, value2: any): boolean
//对象比较
let a = {1,2};
let b = {1,2};
console.log(a === b); //false
console.log(Object.is(a, b)); //false 都是比较的引用值,而不是内容
//基本数据类型比较
const h = 'we';
const j = 'we';
console.log(h === j); //true
console.log(Object.is(h, j)); //true
2.assign() 将后面的对象合并到目标对象(第一个参数)中 Object.assign(target,obj1,boj2..)
let newObj = Object.assign({
a: 1,
add() {
this.a + 2;
}
}, {
b: 2
}, {
a: 3
});
console.log(newObj); //{a: 3, b: 2} 若后面的对象与target对象有相同的属性名,则会覆盖
6.数组的扩展功能
1.from
将伪数组转换成真正的数组
//伪数组转换成真正的数组
let arr = [].slice.call(arguments);
console.log(arr);
let arr2 = Array.from(arguments); //from
console.log(arr2);
let arr3 = [...arguments]; //...
console.log(arr3);
Array.from(数组,回调函数) 回调函数对数组中的每个元素进行处理
let lis = document.querySelectorAll('li');
//Array.from(数组,回调函数) 回调函数对数组中的每个元素进行处理
let liContents = Array.from(lis, ele => ele.textContent);
console.log(liContents);
2.of() 将任意类型的一组值,转换成数组
console.log(Array.of(1, {a: 1}, [2, 3])); //[1, {…}, Array(2)]
3.find() findIndex()
find() 找出第一个符合条件的元素 findIndex()找出第一个符合条件的元素索引
let num = [1, 2, -10, -20, 9, 2].find(n => n < 0);
console.log(num); //-10
let numIndex = [1, 2, -10, -20, 9, 2].findIndex(n => n < 0);
console.log(numIndex); //2
4.copywithin() 从第二个参数处开始到最后复制到第一个参数的位置,从数量不变,覆盖。不常用
console.log([1, 2, 3, 8, 9, 10].copyWithin(0, 2)); //[3, 8, 9, 10, 9, 10]
5.entries() keys() values() 返回一个遍历器Array Iterator {}
for ... of 循环遍历
const arr = ["a", "b", "c"];
for (let index of arr.keys()) {
console.log(index);
}
for (let ele of arr.values()) {
console.log(ele);
}
for (let [index, ele] of arr.entries()) {
console.log(index, ele);
}
6.includes() 返回Boolean,数组中是否包含某个值
[1,2,3].includes(2);
true
[1,2,3].includes('2');
false
[1,2,3].indexOf('2');
-1