Warning: Undefined array key "HTTP_ACCEPT_LANGUAGE" in /www/wwwroot/blog.somekey.cn/usr/themes/Joe/public/tencent_protect.php on line 40

Deprecated: strpos(): Passing null to parameter #1 ($haystack) of type string is deprecated in /www/wwwroot/blog.somekey.cn/usr/themes/Joe/public/tencent_protect.php on line 40
JavaScript中Array对象方法(4) - 桃子🍑关键词

JavaScript中Array对象方法(4)

admin
2022-11-04 / 0 评论 / 135 阅读 / 正在检测是否收录...

Array

数组是一种类列表对象,它的原型中提供了遍历和修改元素的相关操作。JavaScript 数组的长度和元素类型都是非固定的。因为数组的长度可随时改变,并且其数据在内存中也可以不连续,所以 JavaScript 数组不一定是密集型的,这取决于它的使用方式。

图片.png

常用方法

flat()

会按照一个可指定的深度递归遍历数组,并将所有元素与遍历到的子数组中的元素合并为一个新数组返回。
var arr1 = [1, 2, [3, 4]];
arr1.flat();
// [1, 2, 3, 4]

var arr2 = [1, 2, [3, 4, [5, 6]]];
arr2.flat();
// [1, 2, 3, 4, [5, 6]]

var arr3 = [1, 2, [3, 4, [5, 6]]];
arr3.flat(2);
// [1, 2, 3, 4, 5, 6]

//使用 Infinity,可展开任意深度的嵌套数组
var arr4 = [1, 2, [3, 4, [5, 6, [7, 8, [9, 10]]]]];
arr4.flat(Infinity);
// [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

find()

返回数组中满足提供的测试函数的第一个元素的值。否则返回 undefined
const array1 = [5, 12, 8, 130, 44];

const found = array1.find(element => element > 10);

console.log(found);
// expected output: 12

findIndex()

返回数组中满足提供的测试函数的第一个元素的索引。若没有找到对应元素则返回-1。
const array1 = [5, 12, 8, 130, 44];

const isLargeNumber = (element) => element > 13;

console.log(array1.findIndex(isLargeNumber));
// expected output: 3

findLast()

返回数组中满足提供的测试函数条件的最后一个元素的值。如果没有找到对应元素,则返回undefined
const array1 = [5, 12, 50, 130, 44];

const found = array1.findLast((element) => element > 45);

console.log(found);
// expected output: 130

findLastIndex()

返回数组中满足提供的测试函数条件的最后一个元素的索引。若没有找到对应元素,则返回 -1。
const array1 = [5, 12, 50, 130, 44];

const isLargeNumber = (element) => element > 45;

console.log(array1.findLastIndex(isLargeNumber));
// expected output: 3  (of element with value: 30)

这个拥有很多语法

// Arrow function
findLastIndex((element) => { /* ... */ } )
findLastIndex((element, index) => { /* ... */ } )
findLastIndex((element, index, array) => { /* ... */ } )

// Callback function
findLastIndex(callbackFn)
findLastIndex(callbackFn, thisArg)

// Inline callback function
findLastIndex(function(element) { /* ... */ })
findLastIndex(function(element, index) { /* ... */ })
findLastIndex(function(element, index, array){ /* ... */ })
findLastIndex(function(element, index, array) { /* ... */ }, thisArg)

findLastIndex() 方法不会改变调用它的数组,但是提供的 callbackFn 可以。findLastIndex() 处理的元素是在第一次调用 callbackFn 之前设置的。因此:

  • callbackFn 不会访问在调用 findLastIndex() 开始后才添加到数组中的任何元素。
  • 给已访问过的索引重新赋值将不会被 callbackFn 重新访问。
  • 给初始的范围外的索引赋值,其将不会被 callbackFn 访问。
  • 如果 callbackFn 更改了数组中现有的、尚未访问的元素,则其传递给 callbackFn 的值将是 findLastIndex()访问该元素索引时的值。
  • 仍然会访问已删除的元素。

使用箭头函数

const fruits = ["apple", "banana", "cantaloupe", "blueberries", "grapefruit"];

const index = fruits.findLastIndex(fruit => fruit === "blueberries");

console.log(index); // 3
console.log(fruits[index]); // blueberries
0

评论

博主关闭了所有页面的评论