当前位置:网站首页>JS determines whether an object is empty

JS determines whether an object is empty

2022-07-07 13:08:00 Dax1_

1. for…in

utilize for...in Traversing objects , If the object has properties, return “ Non empty ”, Otherwise return to “ empty ”

        function fn(obj) {
    
            for (let key in obj) {
    
                return ' Non empty '
            }
            return ' empty '
        }

2. JSON.Stringify()

utilize JSON.stringify() Serialize objects , If the result after serialization is {}, Then the object is empty

        function fn2(obj) {
    
            let res = JSON.stringify(obj)
            return res === '{}' ? ' empty ' : ' Non empty '
        }

3. Object.keys()

utilize Object.keys() Returns the self of a given object Enumerable properties Array of components , If you return an empty array , Then the given object is an empty object .

        function fn3(obj) {
    
            return Object.keys(obj).length === 0 ? ' empty ' : ' Non empty '
        }
原网站

版权声明
本文为[Dax1_]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/188/202207071100531266.html