如何在JavaScript中的函数之间传递变量?
问题描述:
这里有2个最简单形式的函数.我正在使用jquery.
Here are 2 functions in the simplest form. I'm working with jquery.
将var str从第一个函数传递给第二个函数的最佳方法是什么?
What is the best way to pass var str from the first function to the second one?
function a() {
var str = "first";
};
function b() {
var new = str + " second";
};
答
您需要在它们之间传递它,或者从您的示例看来,只需在更高的范围内声明它即可:
You need to either pass it between them, or it seems from your example, just declare it in a higher scope:
var str;
function a(){
str="first";
}
function b(){
var something = str +" second"; //new is reserved, use another variable name
}