哪种检查变量是否已初始化的方法更好/正确?(假设变量可以保存任何内容(字符串、int、对象、函数等))
if (elem) { // or !elem
or
if (typeof elem !== 'undefined') {
or
if (elem != null) {
哪种检查变量是否已初始化的方法更好/正确?(假设变量可以保存任何内容(字符串、int、对象、函数等))
if (elem) { // or !elem
or
if (typeof elem !== 'undefined') {
or
if (elem != null) {
当前回答
您也可以使用!!在变量之前检查它是否已定义。例如。
let dog = "woof";
let chineseCat; // Undefined.
console.log("1.");
console.log(!!dog && !!chineseCat ? "Both are defined" : "Both are NOT defined");
chineseCat= "mao"; // dog and chineseCat are now defined.
console.log("2.");
console.log(!!dog && !!chineseCat ? "Both are defined" : "Both are NOT defined");
输出:
1.
Both are NOT defined
2.
Both are defined
其他回答
为了有助于辩论,如果我知道变量应该是字符串或对象,我总是喜欢if(!variable),所以检查它是否是假的。这可以带来更干净的代码,例如:
if(数据类型!==“undefined”&&数据类型。url===“未定义”){var message='接收响应时出错';if(typeof data.error!==“undefined”){message=数据错误;}否则如果(数据类型.消息!==“未定义”){message=数据消息;}警报(消息);}
..可以简化为:
if(data&&!data.url){var message=data.error | | data.message | |'接收响应时出错';警报(消息)}
这些答案(除了Fred Gandt解决方案)要么不正确,要么不完整。
假设我需要我的variableName;携带一个未定义的值,因此它是以var variableName等方式声明的;这意味着它已经初始化;-如何检查是否已申报?
或者更好——我如何立即检查“Book1.chapter22.paragraph37”是否存在一次调用,但不会引起引用错误?
我们通过使用最强大的JasvaScript运算符in运算符来实现
"[variable||property]" in [context||root]
>> true||false
为了使if条件正确工作,我们必须使用关键字let来创建变量。
let name = undefined;
if (name) {
alert('valid')
};
我更喜欢这种方法,因为它的准确性和简洁性:
变量x如果(x===无效0){console.log(“x未定义”)}其他{console.log(“x已定义”)}
正如在其他评论和回答中提到的,undefined不能保证是undefineed。因为它不是关键字,所以可以在全局范围以外的范围中将其重新定义为变量。这里有一个小例子可以说明这种细微差别:
var undefined='bar'console.log(`在全局范围内:${undefined}`)函数foo(){var undefined=“已定义”变量x如果(x===未定义){console.log(`x===undefined`)}其他{console.log(`x!==undefined`)}如果(x===无效0){console.log(`x===void 0`)}其他{console.log(`x!==void 0`)}}foo()
请参阅void以了解兼容性(IE5支持!?!!哇!)。
if (typeof console != "undefined") {
...
}
或者更好
if ((typeof console == "object") && (typeof console.profile == "function")) {
console.profile(f.constructor);
}
适用于所有浏览器