我试图通过函数将变量返回true或false。我想这样做,所以我只能调用一次ajax,并在一个函数中接收两个变量。但是,我在返回变量时遇到了麻烦。这是我的代码:
var emailExists = false;
var userExists = false;
function checkExisting(emailExists,userExists) {
var emailExists = true;
return emailExists;
}
alert(emailExists);
我想不出的是为什么警报会让我虚假,当我认为它会让我真实时。这个设置有什么问题?非常感谢你!
答案 0 :(得分:1)
你有3个版本的“emailExists”变量:全局一个,checkExisting()的参数,checkExisting()中的本地参数!摆脱除第一个之外的所有。此外,您永远不会调用checkExisting()。
var emailExists = false;
function checkExisting() {
emailExists = true;
}
checkExisting();
alert(emailExists);
或
var emailExists = false;
function checkExisting() {
return true;
}
emailExists = checkExisting();
alert(emailExists);
答案 1 :(得分:0)
var emailExists = false;
var userExists = false;
function checkExisting(emailExists,userExists) {
emailExists = true;
return emailExists;
}
checkExisting(false,true); //FOR EXAMPLE !
alert(emailExists);
你应该调用checkExisting函数,而不需要从var
使用函数体,因为它是在页面上定义的。
答案 2 :(得分:0)
总之......一切。
我认为你是javascript和编程新手?您需要进行大量阅读,以便了解对象范围以及javascript的工作原理。我会快速介绍一下你所写的内容,以便你能够学到一些东西。
// Here you're declared two objects. 'emailExists' and 'userExists'.
// These Boolean objects, since they are not wrapped in a closure are now global
// (you can reference them anywhere) in your script.
var emailExists = false;
var userExists = false;
// This function never gets called. If it did, it would always return true
// since you have created a new 'emailExists' Boolean object in your function
// and would return that each time.
function checkExisting(emailExists,userExists) {
// This whilst only available within the function closure, is a no, no.
// You're just confusing things by creating objects with the same name
// as global ones.
var emailExists = true;
// I'm returning true.
return emailExists;
}
// Here you are returning your first declared Boolean (the one at the top)
// this will always return false.
alert(emailExists);