繁体   English   中英

我可以将变量从一个 function 传递到另一个 javascript 吗?

[英]Can I pass variable from one function to another in javascript?

我正在学习 Javascript。 我想将变量从一个 function 传递给另一个。 我试图在funTwo中捕获option ,但我不想将变量声明为全局变量或使用var

function funOne(one) {
   let tags = '<div class= "options">' + arr[1] + '</div>';
   const option = options_list.querySelectorAll(".options")
}

function funTwo(two) {
   option.classList.add("correct")
}

在 javascript 中,用constlet声明的变量是作用域的:这意味着它们存在并且只能在当前的 scope 中访问。

When you declare a variable inside a function, it is inside the function scope and inaccessible from anything that is not in that scope, including other functions. 如果要使用此变量,则需要将其作为参数传递或从 function 调用中返回。

function b(value) {
    console.log(value);
}

function a() {
    const foo = 1;
    b(foo);
}

或者

function b() {
    let value = a();
    console.log(value);
}

function a() {
    return 1;
}

是的,您可以从 funOne 返回选项并在 funTwo 中获取。

  function funOne(one){
  let tags = '<div class = "options">' + arr[1] + '</div>'
  const option = options_list.querySelectorAll(".options")
  return option
 }

 function funTwo(two){
  const option = funOne() // the function will return option.
  option.classList.add("correct")
}

暂无
暂无

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

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