使用javascript将函数返回值分配给某些变量 [英] assign function return value to some variable using javascript
问题描述
我有一个js函数,经过一些业务逻辑后,javascript函数应该将结果返回到另一个变量.下面的示例代码
I have a js function , after doing some business logic, the javascript function should return some result to another variable.Sample code below
var response="";
function doSomething() {
$.ajax({
url:'action.php',
type: "POST",
data: dataString,
success: function (txtBack) {
if(txtBack==1) {
status=1;
}
});
return status;
}
我想在这里使用
response=doSomething();
我想分配一个返回值"status""var response".但是结果是'undefined'.
I want to assign a return value "status" "var response".But the result is 'undefined'.
推荐答案
或者只是...
var response = (function() {
var a;
// calculate a
return a;
})();
在这种情况下,响应变量接收函数的返回值.该函数立即执行.
In this case, the response variable receives the return value of the function. The function executes immediately.
如果要使用需要计算的值填充变量,则可以使用此构造.请注意,所有计算都在匿名函数内部进行,因此您不会污染全局名称空间.
You can use this construct if you want to populate a variable with a value that needs to be calculated. Note that all calculation happens inside the anonymous function, so you don't pollute the global namespace.
这篇关于使用javascript将函数返回值分配给某些变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!