//箭头函数
const add = (a, b) => {
return a + b
};
console.log(add(10, 20));
//如果只有一条语句 可以不用{};
//如果这一条语句 是返回表达式,可以不用return
const one = (a) => a * a;
console.log(one(10));
//如果只有一个形参,可以不用();
//如果没有参数或两个及两个以上的参数必须用();
const two = a => a * a;
console.log(two(2));
//如果返回对象时,必须在外面用()
const obj = () => ({
a: "222", b: "111", say() {
//箭头函数的自身是没有 this的,在哪调用 就是哪父类,和调用者无关,是继承而来
//console.log(this);//{a: '222', b: '111', say: ƒ}//相当于是 obj()
return this.a;
}
});
var res = obj().say();
console.log(obj());//{a: '222', b: '111', say: ƒ}
console.log(res);//222
let arr = [1, 2, 3, 51, 12, 41, 421, 23];
//排序
console.log(arr.sort((a, b) => a - b));
// for-of变量是将arr的值给n;for-in 是将下标给n
for (let n of arr) {
console.log(n);
}
//过滤 arr.filter(n=>n>10) 得到一个大于10的数组
//arr.filter(n=>n>10).map(n=>n*0.5) 遍历大于10 的数组 各个值*0.5 得到一个新的数组 b
//b.reduce((s,n)=>s+n) 计算数组各个值 之和
let result = arr.filter(n => n > 10).map(n => n * 0.5).reduce((s, n) => s + n)
console.log(result);//274
setTimeout(() => {
console.log('----------')
}, 100);
//模板字符串 ` `反引号
let aString = `<h1>
<div>
${arr}
</div>
</h1>`
console.log(aString)
/*
<h1>
<div>
1,2,3,12,23,41,51,421
</div>
</h1>
*/
//解构赋值,左右两边结构一模一样
//左边的元素可以比右边少,从左往右 挨个赋值,少几个右边后面的就不赋值
//对象解构赋值:左边的元素是右边对象的键名;
let [one1, two1, three] = ['aaa', 'bbb', 'ccc']
console.log(one1);//aaa
console.log(two1);//bbb
console.log(three);//ccc
let {name, age, sex} = {name: 'zhang', age: 18, sex: 'nv'}
console.log(name);//zhang
console.log(age);//18
console.log(sex);//nv
//展开(扩展)运算符...
let arr1= [1,2,3];
console.log(...arr1);//1 2 3
let arr2=['aaa',...arr1,'bbb','ccc']
console.log(arr2);//['aaa', 1, 2, 3, 'bbb', 'ccc']
function fun(...arr) {
return arr;
}
console.log(fun(1, 2, 3));// [1, 2, 3]