我要在这里实现的是,我做了一个简单的实用函数,并且应该根据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]) ))
答案 0 :(得分:2)
在函数上使用Object.keys()
将始终导致空数组(无论返回类型如何)。这是由于以下事实:函数的键不可枚举(键为name
和length
),而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 }
}