mozilla
您的搜索结果

    Array.prototype.findIndex()

    该特性目前仍处于 ECMAScript 6 规范草案中
    目前的实现在未来可能会发生改变,甚至被完全删除,请谨慎使用。

    概述

    findIndex() 函数用来查找数组中某指定元素的索引, 如果找不到指定的元素, 则返回 -1.

    语法

    arr.findIndex(callback[, thisObject])

    参数

    callback
    针对数组中的每个元素, 都会执行该回调函数, 执行时会自动传入下面三个参数:
    element
    当前元素.
    index
    当前元素的索引.
    array
    数组本身.
    thisObject
    执行 callback 时 this 的值.

    描述

    The findIndex method executes the callback function once for each element present in the array until it finds one where callback returns a true value. If such an element is found, findIndex immediately returns the index of that element. Otherwise, findIndex returns -1. callback is invoked only for indexes of the array which have assigned values; it is not invoked for indexes which have been deleted or which have never been assigned values.

    callback is invoked with three arguments: the value of the element, the index of the element, and the Array object being traversed.

    If a thisObject parameter is provided to findIndex, it will be used as the this for each invocation of the callback. If it is not provided, or is null, the global object associated with callback is used instead.

    findIndex does not mutate the array on which it is called.

    The range of elements processed by findIndex is set before the first invocation of callback. Elements that are appended to the array after the call to findIndex begins will not be visited by callback. If an existing, unvisited element of the array is changed by callback, its value passed to the visiting callback will be the value at the time that findIndex visits that element's index; elements that are deleted are not visited.

    示例

    示例1: 查找数组中首个质数元素的索引

    下面的示例演示了如何查找一个数组中首个质数元素的索引, 找不到则返回 -1.

    function isPrime(element, index, array) {
        var start = 2;
        while (start <= Math.sqrt(element)) {
            if (element % start++ < 1) return false;
        }
        return (element > 1);
    }
    
    console.log( [4, 6, 8, 12].findIndex(isPrime) ); // -1, 没找到质数元素
    console.log( [4, 6, 7, 12].findIndex(isPrime) ); // 2
    

    规范

    Specification Status Comment
    ECMAScript 6 (ECMA-262)
    Array.prototype.findIndex
    Draft Initial definition.

    浏览器兼容性

    Help improve compatibility tables by filling out this 11 question survey.

    Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari
    Basic support Not supported 25.0 (25.0) Not supported Not supported Not supported
    Feature Android Chrome for Android Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile
    Basic support Not supported Not supported 25.0 (25.0) Not supported Not supported Not supported

    相关链接

    文档标签和贡献者

    此页面的贡献者有: ziyunfei, teoli
    最后编辑者: ziyunfei,