有没有一种方法可以检查Javascript函数返回的对象/数组是否为空?

时间:2019-11-20 06:18:01

标签: javascript arrays object

我要在这里实现的是,我做了一个简单的实用函数,并且应该根据isEmpty方法的给定参数返回“ true”或“ false”。

//下面的日志应该返回'false',但是它返回'true'

console.log(isEmpty( () => {key: 1} )); 

到目前为止我尝试过的事情

 function isEmpty(value) {
  const type = typeof value;
    if ((value !== null && type === 'object') || type === 'function') {
       const properties = Object.keys(value);
        return properties.length === 0 || properties.size === 0
      } 
      return !value;
   }

它适用于以下情况

        console.log(isEmpty( {} )) // true
        console.log(isEmpty( [] )) // true
        console.log(isEmpty( Object.create(null) )) // true
        console.log(isEmpty( null )) // true
        console.log(isEmpty( '' )) // true

        console.log(isEmpty( {key: 1} )) // false
        console.log(isEmpty( [1,2,3] )) // false

但是,当我们从函数中获取返回对象/数组时,它不起作用

    console.log(isEmpty( () => ({key: 1}) )) 
    console.log(isEmpty( () => ([1,2,3]) )) 

2 个答案:

答案 0 :(得分:2)

在函数上使用Object.keys()将始终导致空数组(无论返回类型如何)。这是由于以下事实:函数的键不可枚举(键为namelength),而Object.keys()仅返回可以枚举的键。这意味着键数组的长度将始终为0,这意味着即使传递的函数返回非空值,您的函数也将返回true

如果您可以调用value(如果它是一个函数),它将允许您从中获取返回值(即:对象或数组),然后使用您的函数进行递归当前具有:

function isEmpty(value) {
  const type = typeof value;
  if (value !== null && type === 'object') {
    const prototype = Object.getPrototypeOf(value) || {};
    const properties = Object.keys(value) + Object.keys(prototype);
    return properties.length === 0 || properties.size === 0
  } else if(type === 'function') {
    const res = value();
    return isEmpty(res);
  }
  return !value;
}

console.log(isEmpty( {} )) // true
console.log(isEmpty( [] )) // true
console.log(isEmpty( Object.create(null) )) // true
console.log(isEmpty( null )) // true
console.log(isEmpty( '' )) // true

console.log(isEmpty(() => ({}))); // true
console.log(isEmpty(() => () => () => ({}))); // true

console.log(isEmpty( {key: 1} )) // false
console.log(isEmpty( [1,2,3] )) // false

console.log(isEmpty(() => ({key: 1}))); // false
console.log(isEmpty( () => ([1,2,3]) )) // false


console.log(isEmpty(() => (Object.create({key: 1})))) // false

答案 1 :(得分:1)

要实现此目的,您必须检查value的类型,如果它是function,则调用以获取结果。

如果传递的函数有副作用,则会调用它们,这可能会导致一些问题。

function isEmpty(value) {
    const type = typeof value;

    // If passed a function, invoke it and get the result
    if (type === 'function') {
        value = value();
    }

    if (value && (type === 'object' || type === 'function')) {
        const properties = Object.keys(value);
        return properties.length === 0 || properties.size === 0
    } 

    return !value;
}

调用() => { key: 1 }之类的函数时,实际上是在创建一个看起来像

的函数
function {
    key: 1
}

表示该函数没有返回值。相反,您应该像这样() => ({ key: 1 })使用它,它将创建一个 功能类似:

function {
    return { key: 1 }
}

https://babeljs.io/repl#?babili=false&browsers=&build=&builtIns=false&spec=false&loose=false&code_lz=MYewdgzgLgBAYgVzMAjDAvDAFASgwPhgG8YBrAUwE8AuGNAXwChRJZFkAmDbPdQrEhRp0Y9HEA&debug=false&forceAllTransforms=false&shippedProposals=false&circleciRepo=&evaluate=false&fileSize=false&timeTravel=false&sourceType=module&lineWrap=true&presets=es2015%2Creact%2Cstage-2&prettier=false&targets=&version=7.7.3&externalPlugins=