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

Jor*_*elf 3 javascript node.js

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

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

问题在于,当我将我的价值观设定在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;
Run Code Online (Sandbox Code Playgroud)

当我检查控制台时,我得到in hereexecute this消息之前的信息.这就是为什么我不知道为什么send不知道是什么newval.

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

ssu*_*ube 10

let并且const都是明显的块范围,不像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
Run Code Online (Sandbox Code Playgroud)

如果要设置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);
Run Code Online (Sandbox Code Playgroud)