zl程序教程

您现在的位置是:首页 >  其它

当前栏目

_.fill(array, value, [start=0], [end=array.length])

value Array start length end _. fill
2023-09-11 14:15:02 时间

11

_.fill(array, value, [start=0], [end=array.length])
_.fill方法用一个固定值填充一个数组中从起始索引到终止索引内的全部元素。不包括终止索引
参数

array (Array): 需要填充的数组
value (*): 给定填充值
[start=0] (number): 起始索引
[end=array.length] (number): 结束索引

返回值

(Array):返回处理好的数组

例子

var array = [1, 2, 3];
 
_.fill(array, 'a');
console.log(array);
// => ['a', 'a', 'a']
 
_.fill(Array(3), 2);
// => [2, 2, 2]
 
_.fill([4, 6, 8, 10], '*', 1, 3);
// => [4, '*', '*', 10]

源代码:

/**
 * lodash (Custom Build) <https://lodash.com/>
 * Build: `lodash modularize exports="npm" -o ./`
 * Copyright jQuery Foundation and other contributors <https://jquery.org/>
 * Released under MIT license <https://lodash.com/license>
 * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
 * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
 */

/** Used as references for various `Number` constants. */
var INFINITY = 1 / 0,
    MAX_SAFE_INTEGER = 9007199254740991,
    MAX_INTEGER = 1.7976931348623157e+308,
    NAN = 0 / 0;

/** Used as references for the maximum length and index of an array. */
var MAX_ARRAY_LENGTH = 4294967295;

/** `Object#toString` result references. */
var funcTag = '[object Function]',
    genTag = '[object GeneratorFunction]',
    symbolTag = '[object Symbol]';

/** Used to match leading and trailing whitespace. */
var reTrim = /^\s+|\s+$/g;

/** Used to detect bad signed hexadecimal string values. */
var reIsBadHex = /^[-+]0x[0-9a-f]+$/i;

/** Used to detect binary string values. */
var reIsBinary = /^0b[01]+$/i;

/** Used to detect octal string values. */
var reIsOctal = /^0o[0-7]+$/i;

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

/** Built-in method references without a dependency on `root`. */
var freeParseInt = parseInt;

/** Used for built-in method references. */
var objectProto = Object.prototype;

/**
 * Used to resolve the
 * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
 * of values.
 */
var objectToString = objectProto.toString;

/**
 * The base implementation of `_.clamp` which doesn't coerce arguments.
 *
 * @private
 * @param {number} number The number to clamp.
 * @param {number} [lower] The lower bound.
 * @param {number} upper The upper bound.
 * @returns {number} Returns the clamped number.
 */
//_.clamp基础实现,返回一个值,如果介于lower和upper区间之间,就返回原值,否则返回区间的端点
function baseClamp(number, lower, upper) {
  if (number === number) {//排除NaN
    if (upper !== undefined) {
      number = number <= upper ? number : upper;//判断number是否大于区间右端点
    }
    if (lower !== undefined) {
      number = number >= lower ? number : lower;//判断number是否小于区间左端点
    }
  }
  return number;
}

/**
 * The base implementation of `_.fill` without an iteratee call guard.
 *
 * @private
 * @param {Array} array The array to fill.
 * @param {*} value The value to fill `array` with.
 * @param {number} [start=0] The start position.
 * @param {number} [end=array.length] The end position.
 * @returns {Array} Returns `array`.
 */
//_.fill的基础实现
//array需要处理的数组,value固定值,start起始索引,end终止索引
function baseFill(array, value, start, end) {
  var length = array.length;//数组长度

  start = toInteger(start);//起始索引转换成整数
  if (start < 0) {//起始索引小于0情况处理,取相反数后如果大于数组长度,就等于0;否则等于length + start
    start = -start > length ? 0 : (length + start);
  }
  end = (end === undefined || end > length) ? length : toInteger(end);
  //处理结束索引,如果end为undefined或者end大于数组长度,end就等于数组长度;否则将end转换成整数
  if (end < 0) {//如果end是负数,end等于length + end
    end += length;
  }
  end = start > end ? 0 : toLength(end);
  //如果起始索引大于结束索引,结束索引变0,否则用toLength转换end
  while (start < end) {//从起始索引开始循环直到结束索引
    array[start++] = value;//赋值为给定填充值
  }
  return array;//返回处理好的array
}

/**
 * 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 的 index
//value是index值,length是对象的length属性
function isIndex(value, length) {
  length = length == null ? MAX_SAFE_INTEGER : length;//处理length
  return !!length &&
    (typeof value == 'number' || reIsUint.test(value)) &&
    (value > -1 && value % 1 == 0 && value < length);
    //length存在且value是数字或者value是整数,并且value不是负数,并且value不是小数,并且value小于length
}

/**
 * Checks if the given arguments are from an iteratee call.
 *
 * @private
 * @param {*} value The potential iteratee value argument.
 * @param {*} index The potential iteratee index or key argument.
 * @param {*} object The potential iteratee object argument.
 * @returns {boolean} Returns `true` if the arguments are from an iteratee call,
 *  else `false`.
 */

//判断参数是否是一个遍历方法的参数,也就是需要和Array.map的参数一样,第一个是值,第二个是索引,第三个是对象本身
//_.fill这里使用的时候第一个参数是数组,第二个参数是给定填充值,第三个参数是起始索引
function isIterateeCall(value, index, object) {
  if (!isObject(object)) {//如果object不是object,返回false
    return false;
  }
  var type = typeof index;//index的类型
  if (type == 'number'
        ? (isArrayLike(object) && isIndex(index, object.length))
        : (type == 'string' && index in object)
      ) {
        //如果index的类型不是number,就判断object是否是array-like对象,且index是object的有效index
        //如果index的类型是number,判断index是否是string类型,且object有index这个属性
    return eq(object[index], value);//返回object[index]和value是否相等
  }
  return false;
}

/**
 * Fills elements of `array` with `value` from `start` up to, but not
 * including, `end`.
 *
 * **Note:** This method mutates `array`.
 *
 * @static
 * @memberOf _
 * @since 3.2.0
 * @category Array
 * @param {Array} array The array to fill.
 * @param {*} value The value to fill `array` with.
 * @param {number} [start=0] The start position.
 * @param {number} [end=array.length] The end position.
 * @returns {Array} Returns `array`.
 * @example
 *
 * var array = [1, 2, 3];
 *
 * _.fill(array, 'a');
 * console.log(array);
 * // => ['a', 'a', 'a']
 *
 * _.fill(Array(3), 2);
 * // => [2, 2, 2]
 *
 * _.fill([4, 6, 8, 10], '*', 1, 3);
 * // => [4, '*', '*', 10]
 */
//用一个固定值填充一个数组中从起始索引到终止索引内的全部元素。不包括终止索引
//array需要处理的数组,value固定值,start起始索引,end终止索引
function fill(array, value, start, end) {
  var length = array ? array.length : 0;//数组长度
  if (!length) {//如果数组长度为0,返回空数组
    return [];
  }
  if (start && typeof start != 'number' && isIterateeCall(array, value, start)) {
    //如果start存在且不是数字且array,value,start符合遍历方法的参数
    //start赋值为0,end赋值为array长度
    start = 0;
    end = length;
  }
  return baseFill(array, value, start, end);//调用基础实现
}

/**
 * Performs a
 * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
 * comparison between two values to determine if they are equivalent.
 *
 * @static
 * @memberOf _
 * @since 4.0.0
 * @category Lang
 * @param {*} value The value to compare.
 * @param {*} other The other value to compare.
 * @returns {boolean} Returns `true` if the values are equivalent, else `false`.
 * @example
 *
 * var object = { 'a': 1 };
 * var other = { 'a': 1 };
 *
 * _.eq(object, object);
 * // => true
 *
 * _.eq(object, other);
 * // => false
 *
 * _.eq('a', 'a');
 * // => true
 *
 * _.eq('a', Object('a'));
 * // => false
 *
 * _.eq(NaN, NaN);
 * // => true
 */
//判断两个值是否相等
function eq(value, other) {
  return value === other || (value !== value && other !== other);
}

/**
 * Checks if `value` is array-like. A value is considered array-like if it's
 * not a function and has a `value.length` that's an integer greater than or
 * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`.
 *
 * @static
 * @memberOf _
 * @since 4.0.0
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is array-like, else `false`.
 * @example
 *
 * _.isArrayLike([1, 2, 3]);
 * // => true
 *
 * _.isArrayLike(document.body.children);
 * // => true
 *
 * _.isArrayLike('abc');
 * // => true
 *
 * _.isArrayLike(_.noop);
 * // => false
 */
//判断一个值是否是一个array-like对象
function isArrayLike(value) {
  return value != null && isLength(value.length) && !isFunction(value);
}

/**
 * Checks if `value` is classified as a `Function` object.
 *
 * @static
 * @memberOf _
 * @since 0.1.0
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is a function, else `false`.
 * @example
 *
 * _.isFunction(_);
 * // => true
 *
 * _.isFunction(/abc/);
 * // => false
 */
//判断一个值是否是一个Function对象
function isFunction(value) {
  // The use of `Object#toString` avoids issues with the `typeof` operator
  // in Safari 8-9 which returns 'object' for typed array and other constructors.
  var tag = isObject(value) ? objectToString.call(value) : '';//如果是object就获取toString tag
  return tag == funcTag || tag == genTag;//toString tag 等于[object Function]或者[object GeneratorFunction]
}

/**
 * Checks if `value` is a valid array-like length.
 *
 * **Note:** This method is loosely based on
 * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).
 *
 * @static
 * @memberOf _
 * @since 4.0.0
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is a valid length, else `false`.
 * @example
 *
 * _.isLength(3);
 * // => true
 *
 * _.isLength(Number.MIN_VALUE);
 * // => false
 *
 * _.isLength(Infinity);
 * // => false
 *
 * _.isLength('3');
 * // => false
 */
//判断一个值是否是一个有效的array-like对象的length属性
function isLength(value) {
  return typeof value == 'number' &&
    value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;
}

/**
 * Checks if `value` is the
 * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)
 * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
 *
 * @static
 * @memberOf _
 * @since 0.1.0
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is an object, else `false`.
 * @example
 *
 * _.isObject({});
 * // => true
 *
 * _.isObject([1, 2, 3]);
 * // => true
 *
 * _.isObject(_.noop);
 * // => true
 *
 * _.isObject(null);
 * // => false
 */
//判断一个值是否是对象,object或者function类型
function isObject(value) {
  var type = typeof value;
  return !!value && (type == 'object' || type == 'function');
}

/**
 * Checks if `value` is object-like. A value is object-like if it's not `null`
 * and has a `typeof` result of "object".
 *
 * @static
 * @memberOf _
 * @since 4.0.0
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is object-like, else `false`.
 * @example
 *
 * _.isObjectLike({});
 * // => true
 *
 * _.isObjectLike([1, 2, 3]);
 * // => true
 *
 * _.isObjectLike(_.noop);
 * // => false
 *
 * _.isObjectLike(null);
 * // => false
 */
//判断一个值是否是一个object-like对象
function isObjectLike(value) {
  return !!value && typeof value == 'object';
}

/**
 * Checks if `value` is classified as a `Symbol` primitive or object.
 *
 * @static
 * @memberOf _
 * @since 4.0.0
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is a symbol, else `false`.
 * @example
 *
 * _.isSymbol(Symbol.iterator);
 * // => true
 *
 * _.isSymbol('abc');
 * // => false
 */
//判断一个值是否是原生的Symbol类型
function isSymbol(value) {
  return typeof value == 'symbol' ||
    (isObjectLike(value) && objectToString.call(value) == symbolTag);
}

/**
 * Converts `value` to a finite number.
 *
 * @static
 * @memberOf _
 * @since 4.12.0
 * @category Lang
 * @param {*} value The value to convert.
 * @returns {number} Returns the converted number.
 * @example
 *
 * _.toFinite(3.2);
 * // => 3.2
 *
 * _.toFinite(Number.MIN_VALUE);
 * // => 5e-324
 *
 * _.toFinite(Infinity);
 * // => 1.7976931348623157e+308
 *
 * _.toFinite('3.2');
 * // => 3.2
 */
//将一个值转换成 有限 的数字
function toFinite(value) {
  if (!value) {//如果value为假,返回0
    return value === 0 ? value : 0;
  }
  value = toNumber(value);//将value转换成number类型
  if (value === INFINITY || value === -INFINITY) {//如果是无限
    var sign = (value < 0 ? -1 : 1);//正负标记
    return sign * MAX_INTEGER;//转换成有限值
  }
  return value === value ? value : 0;//返回结果,如果是NaN就返回0
}

/**
 * Converts `value` to an integer.
 *
 * **Note:** This method is loosely based on
 * [`ToInteger`](http://www.ecma-international.org/ecma-262/7.0/#sec-tointeger).
 *
 * @static
 * @memberOf _
 * @since 4.0.0
 * @category Lang
 * @param {*} value The value to convert.
 * @returns {number} Returns the converted integer.
 * @example
 *
 * _.toInteger(3.2);
 * // => 3
 *
 * _.toInteger(Number.MIN_VALUE);
 * // => 0
 *
 * _.toInteger(Infinity);
 * // => 1.7976931348623157e+308
 *
 * _.toInteger('3.2');
 * // => 3
 */
//将一个值转换成整数
function toInteger(value) {
  var result = toFinite(value),//将value转换成有限值
      remainder = result % 1;//取余获取到小数部分

  return result === result ? (remainder ? result - remainder : result) : 0;
  //如果是NaN返回0,如果是小数,减去小数部分,如果没有小数部分直接返回
}

/**
 * Converts `value` to an integer suitable for use as the length of an
 * array-like object.
 *
 * **Note:** This method is based on
 * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).
 *
 * @static
 * @memberOf _
 * @since 4.0.0
 * @category Lang
 * @param {*} value The value to convert.
 * @returns {number} Returns the converted integer.
 * @example
 *
 * _.toLength(3.2);
 * // => 3
 *
 * _.toLength(Number.MIN_VALUE);
 * // => 0
 *
 * _.toLength(Infinity);
 * // => 4294967295
 *
 * _.toLength('3.2');
 * // => 3
 */
//把一个值转换成整数,适合作为一个array-like的length属性
function toLength(value) {
  return value ? baseClamp(toInteger(value), 0, MAX_ARRAY_LENGTH) : 0;
  //用baseClamp判断value是否在0到MAX_ARRAY_LENGTH区间之中,然后返回区间中的值
}

/**
 * Converts `value` to a number.
 *
 * @static
 * @memberOf _
 * @since 4.0.0
 * @category Lang
 * @param {*} value The value to process.
 * @returns {number} Returns the number.
 * @example
 *
 * _.toNumber(3.2);
 * // => 3.2
 *
 * _.toNumber(Number.MIN_VALUE);
 * // => 5e-324
 *
 * _.toNumber(Infinity);
 * // => Infinity
 *
 * _.toNumber('3.2');
 * // => 3.2
 */
//将一个值转换成数字
function toNumber(value) {
  if (typeof value == 'number') {//如果是number之间返回
    return value;
  }
  if (isSymbol(value)) {//如果是Symbol类型,返回NaN
    return NAN;
  }
  if (isObject(value)) {//如果value是对象
    var other = typeof value.valueOf == 'function' ? value.valueOf() : value;
    //如果value有valueOf属性,就调用valueOf()取值,否则取原值
    value = isObject(other) ? (other + '') : other;//如果other是对象,就转成字符串,否则取原值
  }
  if (typeof value != 'string') {//value被转成字符串后的处理
    return value === 0 ? value : +value;
  }
  value = value.replace(reTrim, '');//正则把空白字符都转换成空字符串
  var isBinary = reIsBinary.test(value);//判断是否是二进制
  return (isBinary || reIsOctal.test(value))
    ? freeParseInt(value.slice(2), isBinary ? 2 : 8)
    : (reIsBadHex.test(value) ? NAN : +value);
    //如果是二进制或者八进制,调用parseInt转换
    //否则判断不良签名的十六进制转为NaN
}

module.exports = fill;