[生态建设] - js判断小技巧

0、参考

说明: 从几个易得的点出发,逐步向外扩展延申,保证代码的可靠性

1、判断是否为某个类型

// 判断是否为 null
const isNull = o => {
    
    
  return o === null;
};

// 判断是否为 undefined
const isUndefined = o => {
    
    
  return o === undefined;
};

// 判断是否为 null or undefined
const isNil = o => {
    
    
  return isNull(o) || isUndefined(o);
};

// 判断是否为 string
const isString = o => {
    
    
  return !isNil(o) && (typeof o === 'string' || o instanceof String);
};

// 判断是否为 number
const isNumber = o => {
    
    
  return !isNil(o) // 不为 null or undefined
    && (
      (!isNaN(o) && isFinite(o)
        && typeof o === 'number'
      ) || o instanceof Number);
};

// 判断是否为 boolean
const isBoolean = o => {
    
    
  return !isNil(o) && (typeof o === 'boolean' || o instanceof Boolean);
};

// 判断是否为 array
const isArray = o => {
    
    
  return !isNil(o) && Array.isArray(o);
}

// 判断是否为 object
const isObject = o => {
    
    
  return ({
    
    }).toString.call(o) === '[object Object]';
}

// 判断 o 为 O 的实例
const isType = (o, O) => {
    
    
  return !isNil(o) && o instanceof O;
}

// 判断是否为 set
const isSet = o => {
    
    
  return isType(o, Set);
}

// 判断是否为 map
const isMap = o => {
    
    
  return isType(o, Map);
}

// 判断是否为 date
const isDate = o => {
    
    
  return isType(o, Date);
}

2、判断是否为空

数字和字符串可以使用o.length === 0来判断,Set和Map型使用o.size === 0,Object类型使用Object.keys(o).length === 0来判断,具体如下:

// 判断是否为空
const isEmpty = o => {
    
    
  if (isArray(o) || isString(o)) {
    
    
    return o.length === 0;
  }

  if (isSet(o) || isMap(o)) {
    
    
    return o.size === 0;
  }

  if (isObject(o)) {
    
    
    return Object.keys(o).length === 0;
  }

  return false;
}

3、获取第i个元素

主要是list、map、set类型

// 获取列表的第i项
const getXItem = (i, list) => {
    
    
  if (!isArray(list) || !isSet(list) || !isMap(list)) {
    
    
    return undefined;
  }

  if (isArray(list)) {
    
    
    return list.slice(i)[0] || undefined;
  }
  if (isSet(list)) {
    
    
    return Array.from(list).slice(i)[0] || undefined;
  }
  if (isMap(list)) {
    
    
    return Array.from(list.value()).slice(i)[0] || undefined;
  }
}

// 获取列表的最后一项
const getLastItem = list => {
    
    
	return getXItem(-1, list);
}

猜你喜欢

转载自blog.csdn.net/piano9425/article/details/112388356
今日推荐