Javascript 节点投诉变量在条件赋值中未定义?
我试图让用户有选择地将Javascript 节点投诉变量在条件赋值中未定义?,javascript,node.js,Javascript,Node.js,我试图让用户有选择地将options参数传递给函数,以覆盖如下默认变量: let methodName = (options && options.methodName) || 'getSpaces'; 但是,当我将此行放入节点CLI时,会出现一个错误:ReferenceError:options未定义 为什么我不能做这种事?像这样做吧 let options; let methodName = (options && options.methodName)
options
参数传递给函数,以覆盖如下默认变量:
let methodName = (options && options.methodName) || 'getSpaces';
但是,当我将此行放入节点CLI时,会出现一个错误:ReferenceError:options未定义
为什么我不能做这种事?像这样做吧
let options;
let methodName = (options && options.methodName) || 'getSpaces';
您试图访问不存在的变量,这就是它抛出此错误的原因。由于相同的原因,如果在浏览器控制台中粘贴相同的代码,也会出现相同的错误。如果您不知道是否会定义
选项,可以执行以下操作:
let methodName = (typeof(options) !== 'undefined' && options.methodName) || 'getSpaces';
函数声明在我看来是错误的。
它可以是以下任一项:
let methodName=(options)=>((options&&options.methodName)| |“getSpaces”);
让otherMethod=(methodName=“getSpaces”)=>(methodName)
console.log(methodName())//getSpaces
log(methodName({methodName:“testMethod”}))//testMethod
console.log(otherMethod())//getSpaces
console.log(otherMethod(“anotherTestMethod”)//anotherTestMethod
检查未定义的工作原理:将函数定义显示为。那么,您在哪里定义了选项?也显示代码的这一部分。@Bergi这正是问题所在,他没有,我假设他直接在节点终端中运行这段代码。@БПццццццццццццццццццц。