_.size(collection)

90

_.size(collection)
_.size获取collection的长度,array-like对象返回length属性,对象类型返回自身可遍历的字符串键属性的个数

参数

collection (Array|Object|string): 需要检查的集合

返回值

(number): 返回集合的大小

例子

_.size([1, 2, 3]);
// => 3
 
_.size({ 'a': 1, 'b': 2 });
// => 2
 
_.size('pebbles');
// => 7

源代码:

import getTag from './.internal/getTag.js'
import isArrayLike from './isArrayLike.js'
import isString from './isString.js'
import stringSize from './.internal/stringSize.js'

/** `Object#toString` result references. */
const mapTag = '[object Map]'
const setTag = '[object Set]'

/**
 * Gets the size of `collection` by returning its length for array-like
 * values or the number of own enumerable string keyed properties for objects.
 *
 * @since 0.1.0
 * @category Collection
 * @param {Array|Object|string} collection The collection to inspect.
 * @returns {number} Returns the collection size.
 * @example
 *
 * size([1, 2, 3])
 * // => 3
 *
 * size({ 'a': 1, 'b': 2 })
 * // => 2
 *
 * size('pebbles')
 * // => 7
 */
//获取collection的长度,array-like对象返回length属性,对象类型返回自身可遍历的字符串键属性的个数
function size(collection) {
  if (collection == null) {//如果collection为空,返回0
    return 0
  }
  if (isArrayLike(collection)) {//如果collection是array-like对象
    return isString(collection) ? stringSize(collection) : collection.length
    //判断collection是否是字符串,如果是字符串就调用stringSize计算字符串长度,否则直接返回collection的length属性
  }
  const tag = getTag(collection)//获取collection的toString tag
  if (tag == mapTag || tag == setTag) {//如果collection是Set或者Map对象,直接返回其size属性
    return collection.size
  }
  return Object.keys(collection).length
  //如果是其他对象类型,使用Object.keys()方法获取到对象自身可遍历的属性组成的数组,然后返回其长度
}

export default size
stringSize
import asciiSize from './asciiSize.js'
import hasUnicode from './hasUnicode.js'
import unicodeSize from './unicodeSize.js'

/**
 * Gets the number of symbols in `string`.
 *
 * @private
 * @param {string} string The string to inspect.
 * @returns {number} Returns the string size.
 */
//返回字符串中字符的个数
function stringSize(string) {
  return hasUnicode(string) ? unicodeSize(string) : asciiSize(string)
  //判断字符串中是否含有unicode字符,如果有调用unicodeSize处理,否则调用asciiSize处理
}

export default stringSize

 

posted @ 2018-11-11 15:23  hahazexia  阅读(614)  评论(0)    收藏  举报