Skip to content

JavaScript列表常用函数

573字约2分钟

JavaScript

2023-06-09

文章整理了JavaScript常用函数。

过滤列表元素--filter

filter()方法创建一个通过条件的新数组。

filter 语法

var newArray = arr.filter(callbackFn(element, [index], [array]), context)
// element 数组中当前正在处理的元素
// index【可选】 正在处理的元素在数组中的索引
// arrray【可选】 filter处理的数组

函数使用

const words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];

const result = words.filter(word => word.length > 6);

console.log(result);

const result1 = words.filter(function (element,index,arr) {
  console.log(arr[index])
  console.log(element)
  return element.length > 6
}, words);

函数输出

Array ["exuberant", "destruction", "present"]
Array ["exuberant", "destruction", "present"]
"spray"
"spray"
"limit"
"limit"
"elite"
"elite"
"exuberant"
"exuberant"
"destruction"
"destruction"
"present"
"present"

修改列表元素--map

map 语法

var newArray = arr.map(callbackFn(element, [index], [array]), context)
// element 数组中当前正在处理的元素
// index【可选】 正在处理的元素在数组中的索引
// arrray【可选】 filter处理的数组

函数使用

const array1 = [1, 4, 9, 16];

// pass a function to map
const map1 = array1.map(x => x * 2);

console.log(map1);
// expected output: Array [2, 8, 18, 32]

const map2 = array1.map(function (element,index,arr) {
  console.log(arr[index])
  console.log(element)
  return element * 2
}, array1);

console.log(map2)

函数输出

Array [2, 8, 18, 32]
1
1
4
4
9
9
16
16
Array [1, 4, 9, 16]

更新列表元素--forEach

forEach 语法

array.forEach(function(currentValue, index, arr))
# currentValue:函数当前处理的值
# index:当前值在列表中索引
# arr:被处理的列表

函数使用

let students = ['John', 'Sara', 'Jack'];

students.forEach(myFunction);

function myFunction(item, index, arr) {
    arr[index] = 'Hello ' + item;
}

console.log(students);

函数输出

["Hello John", "Hello Sara", "Hello Jack"]

查找列表符合条件的第一个元素--find

find 语法

const index = arr.find(callback(element, index, arr),thisArg)
// element 数组中当前正在处理的元素
// index【可选】 正在处理的元素在数组中的索引
// arrray【可选】 filter处理的数组

函数使用

let numbers = [1, 3, 4, 9, 8];

function isEven(element) {
  return element % 2 == 0;
}

let evenNumber = numbers.find(isEven);
console.log(evenNumber);

函数输出

4

查找列表符合条件的第一个元素的位置--findIndex

findIndex 语法

const index = arr.findIndex(callback(element, index, arr),thisArg)
// element 数组中当前正在处理的元素
// index【可选】 正在处理的元素在数组中的索引
// arrray【可选】 filter处理的数组

函数使用

function isOdd(element) {
  return element % 2 !== 0;
}

let numbers = [2, 8, 1, 3, 4];

let firstOdd = numbers.findIndex(isOdd);

console.log(firstOdd);

函数输出

2