ES6基本语法(二)——函数与数组

函数

函数是JavaScript中组织代码的一种方式,它可以提高代码的复用性,并使其更加模块化。

<script>标签中定义函数

你可以在HTML文件的<script>标签内定义函数,或者在JavaScript文件中定义后再引入到HTML中。

<script>
function sayHello() {
  console.log('Hello!');
}
</script>
无参数的函数类型

这种函数不需要传入任何参数就可以执行。

function greet() {
  console.log('Hello, World!');
}
greet(); // 调用函数
有输入参数的函数类型

函数可以根据传入的参数来执行特定的操作。

function add(a, b) {
  return a + b;
}
console.log(add(5, 3)); // 输出8
有默认值的函数

当函数调用时不提供某些参数时,可以设置默认值。

function addWithDefault(a = 0, b = 0) {
  return a + b;
}
console.log(addWithDefault(5)); // 输出5
匿名函数

匿名函数是没有名称的函数,通常用作回调或者立即执行函数。

let anonymousFunction = function() {
  console.log('This is an anonymous function.');
};
anonymousFunction(); // 调用匿名函数
箭头函数

箭头函数是一种更简洁的定义函数的方式,它没有自己的this绑定,适合用于回调。

let arrowFunction = (a, b) => a * b;
console.log(arrowFunction(5, 3)); // 输出15
隐式返回函数

当函数只有一个表达式时,可以直接返回该表达式的值,无需使用return关键字。

let implicitReturn = a => a * 2;
console.log(implicitReturn(5)); // 输出10

数组

  • push:向数组的末尾添加一个或多个元素,并返回数组的新长度。

    let arr = [1, 2, 3];
    arr.push(4);
    console.log(arr); // 输出: [1, 2, 3, 4]
    console.log(arr.push(5, 6)); // 输出: 6
    
  • unshift:向数组的开头添加一个或多个元素,并返回数组的新长度。

    let arr = [1, 2, 3];
    arr.unshift(0);
    console.log(arr); // 输出: [0, 1, 2, 3]
    console.log(arr.unshift(-1, -2)); // 输出: 5
    
  • shift:移除并返回数组的第一个元素。

    let arr = [1, 2, 3];
    let first = arr.shift(); // 移除第一个元素并赋值给first
    console.log(arr); // 输出: [2, 3]
    console.log(first); // 输出: 1
    
  • pop:移除并返回数组的最后一个元素。

    let arr = [1, 2, 3];
    let last = arr.pop(); // 移除最后一个元素并赋值给last
    console.log(arr); // 输出: [1, 2]
    console.log(last); // 输出: 3
    
  • splice(start, number):从指定的索引位置开始移除number个元素,并返回这些被移除的元素组成的数组。

    let arr = [1, 2, 3, 4, 5];
    let removed = arr.splice(1, 2); // 从索引1开始移除2个元素
    console.log(arr); // 输出: [1, 3, 5]
    console.log(removed); // 输出: [2, 4]
    
  • reverse:反转数组元素的顺序。

    let arr = [1, 2, 3];
    arr.reverse();
    console.log(arr); // 输出: [3, 2, 1]
    
  • sort:对数组元素进行排序,默认情况下按照字典顺序升序排列。

    let arr = [3, 1, 2];
    arr.sort();
    console.log(arr); // 输出: [1, 2, 3]
    
  • filter:创建一个新的数组,包含原数组中满足条件的所有元素。

    let arr = [1, 2, 3, 4];
    let evenNumbers = arr.filter(num => num % 2 === 0);
    console.log(evenNumbers); // 输出: [2, 4]
    
  • concat:合并两个或多个数组,并返回一个新的数组,不改变原有数组。

    let arr1 = [1, 2];
    let arr2 = [3, 4];
    let combined = arr1.concat(arr2);
    console.log(combined); // 输出: [1, 2, 3, 4]
    
  • 使用for-of循环遍历数组:这是一种现代的、更直观的方式来遍历数组。

    let arr = [1, 2, 3];
    for (let value of arr) {
      console.log(value); // 输出: 1, 2, 3
    }
    
  • 4
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值