我从javascript函数返回,如下所示:
return{"success": true, "message": "Password changed."};
如何在调用此功能时检索这些功能?
答案 0 :(得分:2)
您正在返回一个对象,您可以将其保存在变量中,然后可以访问对象属性。
//function definition
function fun1(){
return{"success": true, "message": "Password changed."};
}
//function calling
var res1 = fun1();
//using the result returned by function call
if(res1.success)//true
{
alert(res1.message);//"Password changed.
}
答案 1 :(得分:1)
这只是一个对象。只需访问这些属性。
var obj = foo();
for(var key in obj)
console.log(key, " = ", obj[key]);
您也可以仅使用obj.success
和obj.message
来返回后续值。
答案 2 :(得分:0)
那不是“多重回报”;那是返回一个具有属性的对象。所以调用代码接收一个对象,然后使用它的属性:
var a = theFunction();
console.log(a.success);
console.log(a.message);
答案 3 :(得分:0)
function functionReturningObject(){
return{"success": true, "message": "Password changed."};
}
// use a temporary variable!!! this is a valid syntax but will execute twice
// success = functionReturningObject().success
// message = functionReturningObject().message
var map = functionReturningObject();
// when you know it contents you refer it directly
console.log(map.success)
console.log(map.message)
// when you do not know it contents, you can "explore" it
Object.keys(map).forEach(function(key){console.log(key);console.log(map[key]);})
答案 4 :(得分:-1)
喜欢这个吗?
function fn(){
return{"success": true, "message": "Password changed."};
}
fn().success;//true
fn().message;//Password changed.