Skip to content

数组

filter

filter() 方法 返回数组中满足条件的所有元素,若一条都不满足,则返回空数组。

js
const array = [1, 2, 3, 4, 5];
const res = array.filter((d) => d >= 4); // [4, 5]
js
const array = [
  { id: 1, name: "Tom", age: 20 },
  { id: 2, name: "Amy", age: 25 },
  { id: 3, name: "Alice", age: 30 },
  { id: 4, name: "Lucy", age: 20 },
];

const res = array.filter((d) => d.age === 20);
// [{ id: 1, name: "Tom", age: 20 }, { id: 4, name: "Lucy", age: 20 }]

// 优化:解构语法
const res = array.filter(({ age }) => age === 20);

find

find() 方法 返回数组中满足条件的第一个元素,否则返回 undefined。

js
const array = [1, 2, 3, 4, 5];
const res = array1.find((d) => d >= 4); // 4
js
const array = [
  { id: 1, name: "Tom", age: 20 },
  { id: 2, name: "Amy", age: 25 },
  { id: 3, name: "Alice", age: 30 },
  { id: 4, name: "Lucy", age: 20 },
];

const res = array.find((d) => d.age === 20); // [{ id: 1, name: "Tom", age: 20 }]

// 优化:解构方式
const res = array.find(({ age }) => age === 20);

every

every() 方法用于测试 数组内的元素是否全部满足指定条件。若满足,则停止遍历并返回 true,若不满足,则返回 false。

注意

对于空数组,every() 方法永远返回 true。

js
const array = [8, 30, 39, 29, 10, 13]
const result1 = array.every(item => item < 40) // true
const result2 = array.every(item => item < 5)  // false

const array2 = []
const resule3 = arr.every(item => item) // true

at

at() 方法接收一个索引,并返回该索引对应的数组元素,允许正数和负数。负数表示从倒数第一个开始获取。

  • 使用正数时,array[0]array.at(0) 等价;
  • 使用负数时,array[array.length - 1]array.at(-1) 等价;

基本示例:

js
const array = [5, 12, 8, 130, 44];

const res1 = array.at(2)   // 8
const res2 = array.at(-1)  // 44

concat

concat() 方法用于 合并两个或多个数组。该方法不会改变原数组。

基本示例:

js
const array1 = ["a", "b"]
const array2 = [4, 5, 6]

const array3 = array1.concat(array2) // ["a", "b", 4, 5, 6]

entries

entries() 方法返回一个新的 数组迭代器 对象,该对象包含数组中每个元素的 [键, 值] 对。

基础示例:

js
const array = ["a", "b", "c", "d"]
const iterator = array.entries()

console.log(iterator.next().value) // [0, "a"]
console.log(iterator.next().value) // [1, "b"]

示例 2:

js
// for..of循环
for (const element of iterator) {
  console.log(element)
}

Released under the MIT License.