How to determine whether an object is null in es6

WBOY
Release: 2022-04-26 10:51:05
Original
3588 people have browsed it

In es6, you can use the "Object.keys()" method to determine whether the object is null. This method will return an array composed of the enumerable properties of the object itself. The syntax is "alert(Object.keys() Object).length == 0)", if the result is true, the object is null.

How to determine whether an object is null in es6

The operating environment of this tutorial: Windows 10 system, ECMAScript version 6.0, Dell G3 computer.

How to determine whether an object is null in es6

Use the Object.keys() method of ES6

The Object.keys() method will return a An array composed of the enumerable properties of a given object. The return value is also an array composed of the property names in the object.

Examples are as follows:

var data = {};
var arr = Object.keys(data);
alert(arr.length == 0);//true 即为空对象
var datas={a:1,b:2};
var aRR = Object.keys(datas);
console.log(aRR) --> [‘a’,‘b’]
Copy after login

What needs to be noted is:

If data == null, an error will be reported. You need to ensure that the value is not null or undefined

A brief introduction to the Object.keys() method

Pass in the object and return the attribute name

var data={a:1,b:2,c:9,d:4,e:5};
    console.log(Object.keys(data));//["a", "b", "c", "d", "e"]
    Object.keys(data).map((key,item)=>{
        console.log(key,data[key]);//key=>属性名    data[key]=>属性值
});
Copy after login

Pass in the string and return the index

var str = 'ab1234';
console.log(Object.keys(obj));  //[0,1,2,3,4,5]
Copy after login

Pass in the array and return the index

var arr = ["a", "b", "c"];
    console.log(Object.keys(arr)); // console: ["0", "1", "2"]
Copy after login

[Related recommendations: javascript Video tutorialweb front-end

The above is the detailed content of How to determine whether an object is null in es6. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
es6
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template