繁体   English   中英

未识别的'if'中定义的未定义变量

[英]Undefined variable defined inside an 'if' not recognized

我知道这可能有一个非常简单的答案,但我似乎无法弄明白。

我需要根据函数的参数值来定义变量的内容。

问题是,当我将值设置为if我得到ReferenceError: newval is not defined

下面是运行错误的代码的简化版本:

    const myMessage = (recipientId, msg, miller) => {
      const tip = 1;
      if (tip===1) 
        {
        console.log("in here");
        const newval = "some value";
        }
      console.log("executes this");
      const send = newval;

当我检查控制台时,我会in here execute this消息之前in here 这就是为什么我不确定为什么send不知道newval是什么。

任何正确方向的提示将不胜感激,谢谢

letconst都是明显的块范围,与var不同,所以你不能在周围的之外引用它们( 不是函数 ):

function scopes() {
  if (true) {
    var foo = 'visible';
    let bar = 'not visible';
    console.log(foo, bar); // both foo and bar are visible
  }
  console.log(foo, bar); // foo is visible, bar is not
}
console.log(foo, bar); // neither foo nor bar are visible

如果要将const设置为分支的结果,请尝试将分支移动到一个小函数并调用:

function getNewValue(tip) {
  if (tip === 1) {
    // do stuff
    return "some value";
  } else {
    // do other stuff
    return "other value";
  }
}

const tip = 1;
const send = getNewValue(tip);

通常你在块上面声明let和const(如果你需要在块外面)

不要忘记constlet是块级别,也不会被挂起。 var是范围级别并且已提升。

如果你不熟悉它,这里有一个关于吊装的好链接: http//javascriptissexy.com/javascript-variable-scope-and-hoisting-explained/

'use strict';
 const myMessage = (recipientId, msg, miller) => {
   const tip = 1;
   let newval;
   if (tip === 1) {
     console.log("in here");
     newval = "some value";
   }
   console.log("executes this");
   const send = newval;
 }
 myMessage()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM