如何检查变量是否未定义与未在javascript中声明?

如何解决如何检查变量是否未定义与未在javascript中声明?

我知道要查找JavaScript中是否未声明变量,可以使用factory1<T>(ctor?: NoParamConstructor<T>):T{return new ctor}; let a=this.factory<T>() 。如果我将变量声明为未定义(if (typeof variable === 'undefined')),则if语句仍返回true。在JavaScript中,是否有可能发现未声明的变量与值为undefined的变量之间的区别?我知道它们很相似,但是先做var variable = undefined然后再做const variable = undefined会引发错误,因此它们必须不同。

variable = "something else"

我不想使用try catch块,因为我希望能够基于此分配另一个常量。我想要一个这样的解决方案:const variable = undefined if (typeof variable === 'undefined') { console.log('"variable" is undefined') } if (typeof undeclaredVariable === 'undefined') { console.log('"undeclaredVariable" is undefined') },除了const isVariableDeclared = variable === undeclared在javascript中不存在。我知道我可以在try catch块中使用let,但是我正在寻找更优雅的东西。

解决方法

至少在撰写本文时...不,看来您不能做这样的事情:

var a = undeclared(var) ? 'undeclared' : 'undefined'

原因是您不能将未声明的变量传递给函数;即使在非严格模式下,它也会引发错误。

我们能做的就是:

var barIsDeclared = true;

try { bar; }
catch (e) {
  if (e.name == "ReferenceError") {
    barIsDeclared = false;
  }
}

console.log(barIsDeclared);

为什么?

未定义:在声明了变量但未声明变量时发生 被分配了任何值。未定义不是关键字。

未声明:当我们尝试访问任何未声明的变量时会发生 之前使用var或const关键字初始化或声明。如果我们使用 “ typeof”运算符可获取未声明变量的值,我们将 面对运行时错误,返回值为“ undefined”。范围 未声明的变量始终是全局变量。

例如:

  • 未定义:
var a;
undefined
console.log(a) // Success!
  • 未声明:
console.log(myVariable) // ReferenceError: myVariable is not defined

当我们尝试记录undeclared变量时,它将引发错误。尝试记录undefined变量不会。我们制作一个try catch来进行检查。

'use strict'

值得一提的是,在代码中添加'use strict'会验证没有未声明的变量存在,并且如果存在未声明的变量,则会引发错误。

function define() {
 //'use strict' verifies that no undeclared variable is present in our code     
 'use strict';     
 x = "Defined";  
}

define();

ReferenceError: x is not defined

进一步阅读:

,

正如其他人已经指出的那样,OP可能希望区分已声明但未定义的引用和未声明的引用名称...

let declaredButUnassignedAndStrictlyEqualToUndefinedValue;
const declaredAndHavingAssignedTheUndefinedValue = undefined;

// There is no way of telling the above two (un/)assignements appart.

console.log(
  '(declaredButUnassignedAndStrictlyEqualToUndefinedValue === declaredAndHavingAssignedTheUndefinedValue) ?',(declaredButUnassignedAndStrictlyEqualToUndefinedValue === declaredAndHavingAssignedTheUndefinedValue)
);


// the `typeof` operator is of no help
// if it comes to distinguish between
// declared but undefined references
// and undeclared reference names ...

console.log(
  'typeof notDeclaredWithinScope :',typeof notDeclaredWithinScope
);

// ... just a try catch can do that.

try {
  notDeclaredWithinScope;
} catch (err) {
  // console.log(err.message);

  console.log('`notDeclaredWithinScope` does not exist within this scope.')
}
.as-console-wrapper { min-height: 100%!important; top: 0; }

,

我明白你在说什么。没有获得确切答案的定义方法,但是有一种方法可以确定是否定义了答案。只有在某处引用时才可能。

例如: //让我们以为x没有定义

x.substring(1);

输出: ReferenceError:“ x”未定义

因此,如果您使用try catch块方法,则在catch错误消息的帮助下,您可以确定它是否已定义!

,

感谢所有帮助!我已经拼凑了一个简单的解决方案,如果有人需要,它可以满足所有答案中我的需求。唯一的缺点是变量名称必须作为字符串传递。它使用了try catch块,但我仍可以将其用于原始用例(根据其分配常量)。

function declared(variable) {
  let declared = true;
  try {
    eval(variable);
  } catch (e) {
    if (e.name === "ReferenceError") {
      declared = false;
    }
  }
  return declared;
}

let declaredVar;
console.log(declared("declaredVar")); // true
console.log(declared("undeclaredVar")); // false


function typeOf(variable) {
  return eval("typeof " + variable) === "undefined"
    ? declared(variable)
      ? "undefined"
      : "undeclared"
    : eval("typeof " + variable);
}

const stringVar = "string";
const undefinedVar = undefined;
console.log(typeOf("stringVar")); // string
console.log(typeOf("undefinedVar")); // undefined
console.log(typeOf("undeclaredVar")); // undeclared

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-