Open jingchaocheng opened 4 years ago
/** * The base implementation of `findIndex` and `findLastIndex`. * * @private * @param {Array} array The array to inspect. * @param {Function} predicate The function invoked per iteration. * @param {number} fromIndex The index to search from. * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {number} Returns the index of the matched value, else `-1`. */ function baseFindIndex(array, predicate, fromIndex, fromRight) { // 获取 array length const { length } = array // 获取循环 index, 这个根据 fromRight 判断 fromIndex 是 +1 还是 -1 // 在下面循环中会 index-- 和 ++index 会去去除掉 let index = fromIndex + (fromRight ? 1 : -1) // 循环 while ((fromRight ? index-- : ++index < length)) { // 如果 predicate 返回 true,返回当前 index if (predicate(array[index], index, array)) { return index } } // predicate 没有返回 true 循环结束后返回 -1 return -1 } export default baseFindIndex