简体   繁体   English

有没有办法检查 Javascript function 返回 object / 数组是否为空?

[英]Is there a way to check Javascript function returning object / array is empty or not?

What I am trying to achieve here is that, I made a simple utility function and that should return 'true' or 'false', based on the given argument to the isEmpty method.我在这里想要实现的是,我制作了一个简单的实用程序 function,它应该根据 isEmpty 方法的给定参数返回“true”或“false”。

// The below log should return 'false', But it's returning 'true' // 下面的日志应该返回'false',但它返回'true'

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

What I tried so far到目前为止我尝试了什么

 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;
   }

And it's working for below cases它适用于以下情况

        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

But it's not working, when we get the return object / array from the function但它不起作用,当我们从 function 获得返回 object / 数组时

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

Using Object.keys() on a function will always result in an empty array (no matter the return type).在 function 上使用Object.keys()将始终导致一个空数组(无论返回类型如何)。 This is due to the fact that the keys of a function are not enumerable (the keys being name and length ), and Object.keys() will only give back the keys which can be enumerated.这是因为 function 的键是不可枚举的(键是namelength ),并且Object.keys()只会返回可以枚举的键。 This means the length of the array of keys will always be 0 , meaning your function will give back true even though the function it is passed returns a non-empty value.这意味着键数组的长度将始终为0 ,这意味着即使传递的 function 返回非空值,您的 function 也会返回true

If you can invoke the value (if it is a function), it will allow you to get the returned value out of it (ie: an object or array), and then recurse with your function that you currently have:如果您可以调用该value (如果它是一个函数),它将允许您从中获取返回值(即:object 或数组),然后使用您当前拥有的 function 进行递归:

 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

In order to achieve that you will have to check the type of the value and if it is a function then invoke to get the result.为了实现这一点,您必须检查value的类型,如果它是function则调用以获取结果。

If the function passed have side effects they would be called, which could cause some issues.如果通过的 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;
}

When you call a function like () => { key: 1 } you are actually creating a function which looks like当您像() => { key: 1 }这样调用 function 时,您实际上是在创建一个 function

function {
    key: 1
}

which means that the function do not have a return value.这意味着 function 没有返回值。 Instead you should use it like this () => ({ key: 1 }) which will create a function like:相反,您应该像这样() => ({ key: 1 })使用它,这将创建一个 function ,如:

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= 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=

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM