JS(四)JavaScript中的数组操作

JS(四)JavaScript中的数组操作

01 创建数组

1.直接量形式创建数组

const numbers = [1, 2, 3, 4, 5];
const fruits = ['apple', 'banana', 'orange'];

2.使用 Array 构造函数创建数组

const emptyArray = new Array();
const arrayWithLength = new Array(5); // 创建长度为 5 的数组
const arrayWithElements = new Array('apple', 'banana', 'orange');

3.使用 Array.of() 方法创建数组

const numArray = Array.of(1, 2, 3, 4, 5);
const strArray = Array.of('hello', 'world');

4.使用 Array.from() 方法从类数组对象或可迭代对象创建数组

const arrayLike = { length: 4, 0: 'a', 1: 'b', 2: 'c' };
const arrFromObj = Array.from(arrayLike);
console.log(arrFromObj); // 输出: ['a', 'b', 'c',undefined]

const set = new Set(['foo', 'bar', 'baz']);
const arrFromSet = Array.from(set);
console.log(arrFromSet); // 输出: ['foo', 'bar', 'baz']

5.使用扩展运算符(Spread Operator)创建数组

const parts = ['apple', 'banana'];
const wholeFruits = ['orange', ...parts, 'kiwi'];
console.log(wholeFruits); // 输出: ['orange', 'apple', 'banana', 'kiwi']

6.使用 fill() 方法填充数组

const filledArray = new Array(3).fill(0);
console.log(filledArray); // 输出: [0, 0, 0]

02 访问数组元素

1 索引访问

索引来访问数组中的元素
  • 数组的索引是从0开始的。
const fruits = ['apple', 'banana', 'orange'];

console.log(fruits[0]); // 输出第一个元素: 'apple'
console.log(fruits[1]); // 输出第二个元素: 'banana'
console.log(fruits.length); // 输出数组长度: 3
索引修改数组元素
fruits[1] = 'pear';
console.log(fruits); // 输出修改后的数组: ['apple', 'pear', 'orange']

2.数组中的函数访问元素

  • 这边仅介绍几种个人常用的函数
1.push()
  • push 方法用于向数组的末尾添加一个或多个元素,并返回新的长度。
const colors = ['red', 'blue'];
const num= colors.push('green');
console.log(colors); // 输出: ['red', 'blue', 'green']
console.log(num); // 输出: 3
2. pop()
  • pop 方法用于删除并返回数组的最后一个元素。
const colors = ['red', 'blue', 'green'];
const removedColor = colors.pop();
console.log(removedColor); // 输出: 'green'
console.log(colors); // 输出: ['red', 'blue']
3. shift()
  • shift 方法用于删除并返回数组的第一个元素。
const colors = ['red', 'blue', 'green'];
const removedColor = colors.shift();
console.log(removedColor); // 输出: 'red'
console.log(colors); // 输出: ['blue', 'green']
4. unshift()
  • unshift 方法用于向数组的开头添加一个或多个元素,并返回新的长度。
const colors = ['blue', 'green'];
colors.unshift('red');
console.log(colors); // 输出: ['red', 'blue', 'green']
const num=colors.unshift('yellow','black')
console.log(colors);// 输出: ['yellow', 'black', 'red', 'blue', 'green']
console.log(num);// 输出: 5

03 迭代数组

1.使用 for 循环

  • 使用传统的 for 循环来迭代数组,通过索引访问数组元素。
javascriptCopy Codeconst colors = ['red', 'blue', 'green'];
for (let i = 0; i < colors.length; i++) {
  console.log(colors[i]);
}

2.使用 forEach 方法

  • 数组的 forEach 方法可以遍历数组中的每个元素,并对其执行指定的操作。
const colors = ['red', 'blue', 'green'];
colors.forEach(function(color) {
  console.log(color);
});

3. 使用 map 方法

  • map 方法会创建一个新数组,其中的每个元素都是调用回调函数返回的结果。
const numbers = [1, 2, 3];
const doubledNumbers = numbers.map(function(number) {
  return number * 2;
});
console.log(doubledNumbers); // 输出: [2, 4, 6]

4. 使用 for…of 循环

  • ES6 引入的 for...of 循环可以更简洁地遍历数组。
const colors = ['red', 'blue', 'green'];
for (const color of colors) {
  console.log(color);
}

推荐:

  • 在处理大量数据时,for 循环通常比 forEach 方法具有更好的性能
  • 主要是因为 for 循环在内部实现上更为简单和高效。
    • 直接访问索引for 循环允许直接通过索引访问数组元素,而不需要额外的函数调用或迭代器。这样可以减少性能开销,特别是在处理大量数据时。
    • 循环控制for 循环的循环控制条件在循环开始前就被计算好了,而 forEach 方法对于每个元素都需要执行回调函数。在处理大规模数据时,这个额外的回调函数调用可能会导致性能损失。
    • 更少的闭包forEach 方法会创建一个闭包来存储回调函数,而 for 循环不需要额外的闭包。在大数据量情况下,闭包的创建和维护会增加额外的开销。
    • 更少的函数调用forEach 方法每次迭代都需要调用回调函数,而 for 循环不需要进行函数调用,这也会降低性能消耗。

04 查找元素

1.在数组中查找元素
  • 使用 indexOf 方法indexOf 方法用于查找数组中特定元素的索引。如果找到该元素,则返回其索引,否则返回 -1。

    const arr = [1, 2, 3, 4, 5];
    const index = arr.indexOf(3);
    console.log(index); // 输出: 2
    
  • 使用 find 方法find 方法用于查找满足条件的第一个元素,并返回该元素。可以传入一个回调函数作为参数来定义查找条件。

    const arr = [10, 20, 30, 40, 50];
    const result = arr.find(item => item > 25);
    console.log(result); // 输出: 30
    
2. 在对象中查找属性
  • 使用点号或中括号访问属性:可以使用点号或中括号来直接访问对象的属性。

    const obj = { name: 'Alice', age: 30 };
    console.log(obj.name); // 输出: Alice
    console.log(obj['age']); // 输出: 30
    
  • 使用 Object.keysObject.values 方法Object.keys 方法返回对象的所有键组成的数组,可以用于查找属性是否存在。

    const obj = { name: 'Bob', age: 25 };
    const keys = Object.keys(obj);
    if (keys.includes('name')) {
      console.log('Property found');
    }
    const values=Object.values(obj);
    if(values.includes(25)){
        console.log('found');
    }else{
        console.log('never found');
    }
    

05 切片操作

1.数组切片操作
  • 使用数组的 slice 方法可以获取数组的一部分,并返回一个新的数组,而不改变原始数组。slice 方法接受两个参数:起始索引和结束索引(不包括结束索引本身)。
const array = [1, 2, 3, 4, 5];
const slicedArray = array.slice(1, 4);
console.log(slicedArray); // 输出: [2, 3, 4]
  • 在上面的示例中,slice(1, 4) 返回了从索引 1 到索引 3(不包括索引 4)的子数组。
2. 字符串切片操作
  • 对于字符串,可以直接使用类似数组的下标访问来进行切片操作,也可以使用 substringsubstr 方法。

  • 使用下标访问

    const str = "Hello, world!";
    const slicedStr = str.slice(7, 12);
    console.log(slicedStr); // 输出: "world"
    
  • 使用 substring 方法

    const str = "Hello, world!";
    const slicedStr = str.substring(7, 12);
    console.log(slicedStr); // 输出: "world"
    console.log(slicedStr.length); // 输出: 5,不足就是字符串本身长度
    
  • 使用 substr 方法

    const str = "Hello, world!";
    const slicedStr = str.substr(7, 5);
    console.log(slicedStr); // 输出: "world"
    
  • 值得注意的是,substringsubstr 方法的参数分别是起始索引和长度,而不是结束索引。

substring 方法和 substr 方法的区别
1.substring 方法
  • substring(startIndex, endIndex) 方法用于提取字符串从 startIndexendIndex - 1 的部分。
  • 如果 startIndex 大于 endIndexsubstring 会自动交换这两个参数的值。
  • 如果任一参数为负数或超出字符串长度,substring 会将其视为 0。
  • 不支持负数参数。
const str = "Hello, world!";
console.log(str.substring(7, 12)); // 输出: "world"
console.log(str.substring(12, 7)); // 输出: "world"
2. substr 方法
  • substr(startIndex, length) 方法用于从 startIndex 开始提取指定长度的字符。
  • 如果 startIndex 为负数,substr 方法会将其视为从字符串末尾开始的索引。
  • 如果 length 未指定,或者超出了字符串长度,substr 会提取从 startIndex 到字符串末尾的所有字符。
javascriptCopy Codeconst str = "Hello, world!";
console.log(str.substr(7, 5)); // 输出: "world"
console.log(str.substr(-6)); // 输出: "world!"
区别总结
  • 使用方式:substring 使用起始索引和结束索引,而 substr 使用起始索引和长度。
  • 负数处理:substr 允许使用负数索引,而 substring 不支持。
  • 参数处理:substring 在处理不合法参数时会转换为 0,而 substr 则会处理为字符串末尾位置。

其他常用方法

  • filter():根据条件筛选数组元素
  • map():对数组中的每个元素执行函数
  • reduce():将数组元素合并为单个值
  • sort():对数组进行排序
  • some()every():检查数组中是否有元素满足条件或所有元素都满足条件

1.filter()

  • filter() 方法会创建一个新数组,其中包含通过指定函数测试的所有元素。
const numbers = [1, 2, 3, 4, 5];
const evenNumbers = numbers.filter(num => num % 2 === 0);
console.log(evenNumbers); // 输出: [2, 4]

2. map()

  • map() 方法会对数组中的每个元素调用提供的函数,并返回一个新数组。
const numbers = [1, 2, 3];
const squaredNumbers = numbers.map(num => num ** 2);
console.log(squaredNumbers); // 输出: [1, 4, 9]

3. reduce()

  • reduce() 方法会对数组中的每个元素执行一个提供的函数,将其结果汇总为单个值。
const numbers = [1, 2, 3, 4];
const sum = numbers.reduce((acc, curr) => acc + curr, 0);
console.log(sum); // 输出: 10

4. sort()

  • sort() 方法用于对数组元素进行排序,默认是按照 Unicode 码点进行排序。
const fruits = ['apple', 'orange', 'banana'];
fruits.sort();
console.log(fruits); // 输出: ["apple", "banana", "orange"]

5. some()every()

  • some() 方法用于检查数组中是否至少有一个元素满足条件。
  • every() 方法用于检查数组中是否所有元素都满足条件。
const numbers = [1, 2, 3, 4, 5];
const hasEvenNumber = numbers.some(num => num % 2 === 0);
const allEvenNumbers = numbers.every(num => num % 2 === 0);

console.log(hasEvenNumber); // 输出: true
console.log(allEvenNumbers); // 输出: false
  • 25
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

宣布无人罪

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值