布尔变量从javascript函数返回为字符串 [英] Boolean variable returns as string from javascript function
问题描述
为什么当我返回时,我认为是来自javascript函数的布尔变量,它在调用函数中被检测为字符串,但是如果我返回一个布尔文字,则调用函数检测到它作为布尔值?
Why is it that when I'm returning, what I think is, a boolean variable from a javascript function, it is detected in the calling function as a string, but if I return a boolean literal, the calling function detects it as a boolean?
所以,例如:
So, for example:
$( document ).ready(function(){
$('#result').text(typeof validate());
$('#result2').text(typeof validate2());
});
function validate(){
status = true;
status = false;
return status;
}
function validate2(){
return true;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Hello</p>
<div id="result"></div>
<div id="result2"></div>
推荐答案
您没有声明 status
状态变量。
因此,全球的( window.status
)被覆盖。
Therefore, the global one (window.status
) is overwritten.
然而, HTML 5规范将该属性定义为DOMString:
However, the HTML 5 spec defines that property as a DOMString:
interface Window : EventTarget {
attribute DOMString status;
};
因此,它有一个存储字符串值的setter(公开或内部)。
Therefore, it has a setter (either exposed or internal) which stores the stringified value.
要修复它,只需使用 var
声明。
To fix it, just declare your local variable using the var
statement.
这篇关于布尔变量从javascript函数返回为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!