测试javascript中可能不存在的多个值

时间:2018-07-13 15:41:38

标签: javascript

当“成员”和“部门”可能不存在时,测试此状况的正确方法是什么?有没有办法在测试值的同时检查它们的存在而不会引起错误?

if (state.staff.members.length < 5 || state.staff.departments.length < 5) {}

5 个答案:

答案 0 :(得分:2)

最干净(也是我认为最好)的方法是使用try...catch块。这样,如果您要查找的属性不存在,就可以安全而优雅地失败,如下所示:

var state;

function myFunction() {
  try {
    if (state.staff.members.length < 5 || state.staff.departments.length < 5) {
      return "PASS";
    }
  } catch (e) {
    console.log(e.toString());
    return "PASS"
  }
  return "FAIL";
}

console.log(myFunction());

答案 1 :(得分:1)

很多很多虚假的支票

if (
  (
    state &&
    state.staff &&
    state.staff.members &&
    state.staff.members.length < 5
  ) ||
  (
    state &&
    state.staff &&
    state.staff.departments &&
    state.staff.departments.length < 5
  )
) {
   console.log("foo");
}

我建议采用_.get()的lodash方法来封装支票。

if (
    _.get(state, "staff.members.length") < 5 || 
    _.get(state, "staff.departments.length") < 5
){
  console.log("foo");
}

答案 2 :(得分:0)

if ((state.staff.members && state.staff.members.length < 5) || (state.staff.departments && state.staff.departments.length < 5)) {}

这假设您只希望在设置了至少一个属性时通过条件。

编辑:针对您的评论,我将按照以下方式编写

if ((state.staff.members && state.staff.members.length < 5) 
    || (state.staff.departments && state.staff.departments.length < 5)
    || state.staff.hasOwnProperty('members') === false
    || state.staff.hasOwnProperty('departments') === false
) {}

答案 3 :(得分:0)

尝试一下:)

if (
  (state.staff.members && state.staff.members.length < 5) || 
  (state.staff.departments && state.staff.departments.length < 5)
) {

   // do something

}

答案 4 :(得分:0)

对于这些情况,我喜欢使用这样的小帮手:

ng new blah-blah

这是TypeScript,但应该可以理解。并且其他类型信息可能有助于理解。

用法示例:

/**
 * Accesses nested properties and returns a default value if it encounters null or undefined along the way.
 * @param fallback A fallback value if any property or its value is null or undefined.
 * @param path The path to access a nested property
 */
export const propOrDefault = <T, R>(fallback: R) => (...path: string[]) => (obj: T | null | undefined): R =>
  path.reduce((partialObj, propertyName) => {
    if (partialObj && propertyName && partialObj.hasOwnProperty(propertyName)) {
      return partialObj[propertyName] || fallback;
    }

    return fallback;
  }, obj);

如您所见,该助手使用currying,因此您可以像这样预先配置它以供以后使用:

const isValid = propOrDefault(0)('staff', 'members', 'length')(state) < 5;

那里有许多类似的工具,例如lodashramda