How to check if an object exists in js

1. Boolean () method
The Boolean () method can be used to convert any data type in Js into a boolean value:
JS datatype conversion to boolean
2. It is used to determine whether xx exists.
js generally automatically executes the Boolean () method, and we can use this to judge an object Whether it exists in the current execution environment of js. like:

var x = 1;  //  x的数据类型为数值
if (x) {       //   js自动将x转换为布尔值,对应的是true
	代码     //   x为true时if语句执行代码
}

In another example, it can be determined whether an object exists in the current environment.
After binding an event to an element, the browser will pass in an event parameter to its corresponding callback function to save event information related to the current time. like:

element.onclick = function () {
	if(event) {    //  如果event在函数作用域下存在,根据上图原则,js会将其自动转为true
	console.log(1);   //   event为true控制台会输出数字1
	}
}

The event event object exists as a window property in IE8 and below browsers, so there is no event in the function scope, and it needs to be accessed as window.event (global variable). In order to ensure that events can be used in all browsers, the following statements are generally required:

event = event || window.event;

On the right side of the equal sign: if the event exists in the current scope, js will automatically convert it to true, if window.event exists, js will automatically convert it to true, if one of the two sides of the || operator is true, it will be true Assign the value to the variable on the left.

Guess you like

Origin blog.csdn.net/ok060/article/details/131628699