_.nth(array, [n=0])

27

_.nth(array, [n=0])
_nth获取数组在索引n处的元素,如果n值是负数,就加length,相当于从结尾反向寻找
参数

array (Array): 需要被查询的数组
[n=0] (number): 需要被返回的元素的索引

返回值

(*): 返回对应索引的元素

例子

var array = ['a', 'b', 'c', 'd'];
 
_.nth(array, 1);
// => 'b'
 
_.nth(array, -2);
// => 'c';

源代码:

最终的代码中n参数会被toInteger处理变成合法的正整数,此处省略。

import isIndex from './.internal/isIndex.js'

/**
 * Gets the element at index `n` of `array`. If `n` is negative, the nth
 * element from the end is returned.
 *
 * @since 4.11.0
 * @category Array
 * @param {Array} array The array to query.
 * @param {number} [n=0] The index of the element to return.
 * @returns {*} Returns the nth element of `array`.
 * @example
 *
 * const array = ['a', 'b', 'c', 'd']
 *
 * nth(array, 1)
 * // => 'b'
 *
 * nth(array, -2)
 * // => 'c'
 */
//获取数组在索引n处的元素,如果n值是负数,就加length,相当于从结尾反向寻找
function nth(array, n) {
  const length = array == null ? 0 : array.length//数组长度
  if (!length) {//如果长度为0,返回undefined
    return
  }
  n += n < 0 ? length : 0//如果n是负数,就n+length
  return isIndex(n, length) ? array[n] : undefined//isIndex判断n是否是合法索引,如果是返回元素,否则返回undefined
}

export default nth

下面是isIndex

/** Used as references for various `Number` constants. */
const MAX_SAFE_INTEGER = 9007199254740991

/** Used to detect unsigned integer values. */
const reIsUint = /^(?:0|[1-9]\d*)$/

/**
 * Checks if `value` is a valid array-like index.
 *
 * @private
 * @param {*} value The value to check.
 * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.
 * @returns {boolean} Returns `true` if `value` is a valid index, else `false`.
 */
//判断一个值是否是一个合法的array-like对象的索引
function isIndex(value, length) {
  const type = typeof value//value的typeof类型
  length = length == null ? MAX_SAFE_INTEGER : length//处理length值

  return !!length &&
    (type == 'number' ||
      (type != 'symbol' && reIsUint.test(value))) &&
        (value > -1 && value % 1 == 0 && value < length)
        //length不为0的情况下
        //value是number类型或者value不是symbol类型并且是无符号整数
        //value大于-1 并且 value取余1等于0说明没有小数部分 并且 value小于length
}

export default isIndex

 

posted @ 2018-10-15 14:01  hahazexia  阅读(412)  评论(0)    收藏  举报