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
    Release Candidate Initial definition.

    浏览器兼容性

    Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari
    Basic support 未实现 25.0 (25.0) 未实现 未实现 未实现
    Feature Android Chrome for Android Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile
    Basic support 未实现 未实现 25.0 (25.0) 未实现 未实现 未实现

    相关链接

    文档标签和贡献者

    Contributors to this page: teoli, ziyunfei
    最后编辑者: teoli,
    隐藏侧边栏