【エコロジー構築】-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して決定でき、セットタイプとマップタイプを使用しo.size === 0、オブジェクトタイプを使用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番目の要素を取得します

主にリスト、マップ、セットタイプ

// 获取列表的第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