我正在尝试更改将数据写入表的条件.当我试图改变这个时,我注意到了一个奇怪的结果:看起来WriteToTable函数似乎无关紧要,如果我受到它的条件.为了测试这个,我做了以下事情:
var TestThis=0;
if (TestThis=1000){
WriteToTable(iPlaceDisplayNum, place.name, place.rating, xScoreFinal, iProspect, place.url, place.formatted_phone_number);
alert ('This alert should not be displaying.');
}
Run Code Online (Sandbox Code Playgroud)
该函数仍将执行,脚本运行时仍会显示警报.我不知道为什么?
这是函数的其余部分,问题是向下:
function printme(place, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
if (typeof place.reviews !== 'undefined') {
var xScore = 0;
var xGlobal = 0;
for (var i = 0; i < place.reviews.length; i++) {
reviews = place.reviews[i];
for (var x = 0; x < reviews.aspects.length; x++) {
aspectr = reviews.aspects[x];
xScore += aspectr.rating;
xGlobal++;
}
}
var xScoreFinal = (xScore / xGlobal);
}
if (typeof xScoreFinal !== 'undefined') {
iPlaceDisplayNum++;
var iProspect;
if (xScoreFinal < 2.3) {
iProspect = 'Yes';
}
//Not sure what's going on here
var TestThis=0;
if (TestThis=1000){
WriteToTable(iPlaceDisplayNum, place.name, place.rating, xScoreFinal, iProspect, place.url, place.formatted_phone_number);
alert ('This alert should not be displaying.');
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
您在if条件检查中为变量赋值.您的TestThis变量被赋值为1000,在被JavaScript转换为布尔值后将为真.这就是为什么你的功能总是被执行的原因.您可以在此处阅读有关自动类型转换的更多信息.
现在来修复你的代码,改变这个 -
if (TestThis=1000)
Run Code Online (Sandbox Code Playgroud)
对此 -
if (TestThis == 1000)
Run Code Online (Sandbox Code Playgroud)
或者如果您不想自动类型转换 -
if (TestThis === 1000)
Run Code Online (Sandbox Code Playgroud)
有时人们喜欢以下列方式扭转比较中的值 -
if (1000 === TestThis)
Run Code Online (Sandbox Code Playgroud)
这被称为尤达条件(是的,以大绝地大师尤达的名字命名).好处是,如果某人错误地只放置一个相等的,它将导致错误,因为您无法将任何内容分配给常量.我从来没有亲自使用它(也许永远不会,因为我发现它非常传统).