js 数组查找

88 阅读1分钟

Array.findIndex() 方法

传入参数为自定义函数

return满足条件的下标

function getMenuName(id) {
    let menuIds = [
        { id: 1, name: "张三" },
        { id: 2, name: "李四" },
    ];

    let index = menuIds.findIndex((item) => {
        return item.id == id;
    });
    return menuIds[index].name;
}

Array.find()

查找满足特定条件的第一个元素。

var ages = [3, 10, 18, 20];

ages.find((age) => {
    return age >= 18;
});

Array. indexOf() 方法

传入参数为待查找元素

indexOf() 方法可返回某个指定的字符串值在字符串中首次出现的位置。如果没有找到匹配的字符串则返回 -1

var arr = ["a", "b", "c", "d", "e"];
var n = str.indexOf("b");

//n=1

Array.includes()

includes() 方法确定数组是否包含某个值,并在适当时返回 true 或 false

const array = [10, 11, 3, 20, 5];

const includesTwenty = array.includes(20);

console.log(includesTwenty)//true

Array.filter()

return一个新的数组,新数组中的元素是通过检查指定数组中符合条件的所有元素。filter() 不会改变原始数组。

var ages = [32, 33, 16, 40];

let arr = ages.filter((age) => {
    return age >= 18;
});
console.log(arr);//[32,33,40]

Array.map()

返回一个新数组,数组中的元素为原始数组元素调用函数处理后的值。

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

let arr2 = arr.map(item => {
    return Math.sqrt(item);
});

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