ES6 箭头函数
map
foreach
findIndex
find
filter
- 箭头函数
- 写法:
变量名=(参数列表)=>{函数体} - 注意:
- 当参数只有一个时,可以省略参数列表外面的括号()
- 如果函数体只有一句的时候,函数体的括号可以省略{},该语句的值,就是函数的返回值,return可以省略,如果{}不省略的话,return就不能省略
- 箭头函数没有this,如果箭头函数内出现this,要向上找
<script>
//箭头函数
//如果参数只有一个时,参数列表的括号()可以省略
//如果函数体只有一条语句时,{}可以省略,表达式的值,就是函数的返回值,return可省略
let num = (a, b) => {
return a + b;
}
console.log(num(3, 5))//8
//当参数只有一个时
let num1 = r => {
let pi = 3.14;
return pi * r * r;
}
console.log(num1(3))//9*3.14
//当函数体只有一句时
// let num2=(a,b)=>{
// return a-b
// }
let num2 = (a, b) => a - b
console.log(num2(5, 3))//2
//当参数只有一个,函数体只有一句时
// let num3=(a)=>{
// return a*a
// }
let num3 = a => a * a;
console.log(num3(10))//100
</script>
-
-
数组方法对箭头函数的支持
-
map()
-
功能:用当前的数组,生成一个新数组
-
新数组中的元素,都与原数组的元素,有一一对应的关系
-
用法:新数组名=原数组名.map(function)
//map
//功能:用当前的数组,生成一个新数组
//新数组中的元素,都与原数组中的元素有一一对应的关系
//例:创建一个新数组,里面的每个数组都是原数组的平方
let arry = [1, 2, 3, 4, 5]
// let arry1=arry.map(function (item){
// return item*item
// })
let arry1 = arry.map(item => item * item);
console.log(arry1)//[1,4,9,16,25]
例题
//例:有个数组,有三个路径,根据路径生成上面的li,将li放在ul上
let arrar = ['<li>第一个li</li>', '<li>第二个li</li>', '<li>第三个li</li>'];
let arrar1 = arrar.map(item => item);
let ul = document.createElement('ul')
ul.innerHTML = arrar1.join('')
document.body.appendChild(ul)
- forEach()
- 功能:遍历数组
- 用法:数组名.forEach(function)
//foreach
//功能:遍历数组
let array = [1, 2, 3, 5, 9, 10]
// array.forEach(function(a){
// console.log(a);
// })
array.forEach(a => console.log(a));
- findIndex()
- 功能:找到数组中满足条件的第一个值的位置
- 返回索引
- 用法:数组名.findIndex(function)
//findIndex
//找到满足条件的第一值的位置
//返回索引
//例:找到大于3的第一个数的位置
let array = [1, 2, 3, 5, 9, 10];
// array.findIndex(function(item){
// return item>3
// })
console.log(array.findIndex(item => item > 3))//3
- find()
- 功能:返回数组中满足条件的第一个值
- 用法:数组名.find(function)
//find
//返回数组中满足条件的第一个值
//例:找到大于3的第一个数的值
let array = [1, 2, 3, 5, 9, 10];
// array.find(function(item){
// return item>3
// })
console.log(array.find(item => item > 3))//5
- filter()
- 功能:找到数组中满足条件的所有元素
- 用法:数组名.filter(function)
//filter
//返回数组中满足条件的所有值
//例:找到大于3的所有的值
let array = [1, 2, 3, 5, 9, 10];
// array.filter(function(item){
// return item>3
// })
console.log(array.filter(item => item > 3))//[5,9,10]
例题
有个字符串"hello world",将其翻转
//有个字符串"hello world",将其翻转
let str = 'hello world'
let str1 = str.split('').reverse().join('');
console.log(str1)