Js常用数组处理

0 阅读2分钟

数组的遍历 forEach()

const fruits = ["苹果", "香蕉", "橙子"];

// item 代表当前遍历到的那个元素,index 是索引(可选)
fruits.forEach((item, index) => {
  console.log(`第 ${index} 个元素是:${item}`);
});
/*
第 0 个元素是:苹果
第 1 个元素是:香蕉
第 2 个元素是:橙子
*/
  • 替代 for 循环,代码更简洁。

数组静态方法 Array.isArray ()

核心作用判断一个数据到底是不是数组。返回 truefalse

为什么需要它? 因为 typeof 运算符判断数组会返回 object,分不清数组和对象,所以必须用 Array.isArray()

const arr = [1, 2, 3];
const obj = { name: "Jack" };
const num = 123;

console.log(Array.isArray(arr));  // true
console.log(Array.isArray(obj));  // false
console.log(Array.isArray(num));  // false

追加 push ()

核心作用:向数组的末尾添加一个或多个元素。

  • 修改原数组
  • 返回值是新数组的长度。
const animals = ["猫", "狗"];

// 返回值是新长度 3
const newLength = animals.push("猪"); 

console.log(animals);   // ["猫", "狗", "猪"]
console.log(newLength); // 3

头出 shift ()

核心作用:删除数组的第一个元素。

  • 修改原数组
  • 返回值是被删除的那个元素
  • 如果数组为空,返回 undefined
const languages = ["JS", "Java", "Go"];

// 返回被删掉的元素 "JS"
const delItem = languages.shift();

console.log(languages);   // ["Java", "Go"]
console.log(delItem);     // "JS"

批量头出 unshift ()

核心作用:向数组的开头添加一个或多个元素。

  • 修改原数组
  • 返回值是新数组的长度。
const nums = [2, 3];

// 返回新长度 3
const newLength = nums.unshift(1);

console.log(nums);  // [1, 2, 3]

转化字符串 join ()

核心作用:把数组里的所有元素拼接成一个字符串。

  • 不修改原数组,
  • 返回拼接后的字符串。
const chars = ["小", "程", "序"];

// 不传参默认用逗号连接;传参用指定的字符串连接
console.log(chars.join());    // "小,程,序"
console.log(chars.join(""));  // "小程序"
console.log(chars.join("-")); // "小-程-序"

颠倒数组 reverse ()

核心作用:颠倒数组中元素的顺序。

  • 直接修改原数组,
  • 返回值是颠倒后的数组。
const arr = [1, 2, 3, 4];

// 返回颠倒后的数组 [4, 3, 2, 1]
const res = arr.reverse();

console.log(arr);   // [4, 3, 2, 1] (原数组已被改变)
console.log(res);   // [4, 3, 2, 1]

寻值 indexOf ()

核心作用:查找某个元素在数组中第一次出现的位置。

  • 返回索引,找不到返回 -1
  • 严格匹配===),类型不同也找不到(比如 1"1" 算不同)。
const colors = ["红", "黄", "蓝", "黄"];

console.log(colors.indexOf("黄"));  // 1 (只返回第一个匹配的索引)
console.log(colors.indexOf("绿"));  // -1 (找不到)