2013-08-30 117 views
0

我试图改变数据写入表的情况。当我试图改变它的时候,我注意到了一个奇怪的结果:似乎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.'); 
} 

该函数仍将执行,并且脚本运行时仍会显示警报。我不知道为什么?

这里是函数的其余部分,问题是对底部:

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.'); 
     } 

     } 
    } 
} 
+1

只是在你的“测试”中注意到你有=而不是==。但这可能只是一个转位错误? –

+1

你不会相信有多少人有完全相同的问题。 –

回答

7

你在你的,如果条件检查值分配给您的变量。您的TestThis变量被赋值为1000,在通过JavaScript将其转换为布尔值后将为true。这就是为什么你的功能总是被执行。你可以阅读更多关于自动类型转换here

我们解决您的代码,更改此 -

if (TestThis=1000) 

本 -

if (TestThis == 1000) 

,或者如果你不想自动类型转换 -

if (TestThis === 1000) 

有时人们喜欢以下面的方式反转比较中的值 -

if (1000 === TestThis) 

这就是所谓的Yoda Condition(是的,Grand Jedi Master Yoda命名)。好处是,如果有人错误地只把一个平等的,它会导致一个错误,因为你不能给任何常数分配任何东西。我从来没有使用过它(也许永远不会因为我觉得它非常规)。

+0

最好还是养成“if(1000 == TestThis)”的习惯,然后“if(1000 = TestThis)”会导致错误 –

1
if (TestThis == 1000) 

这样的变化。

用于比较,如果你必须有==

4

JavaScript中允许你在条件分配一个值相等,所以这TestThis=1000结果为1000,在条件语句中的正数(实际上什么也没0)结果以评估为真。

使之成为有条件的,你应该做TestThis===1000(和你应该总是使用========迫使两者的实际对比,并不会尝试的一部分转换条件的平等其他)

你也可以做1000 === TestThis(或反过来1000 == TestThis)有人说这是不好的代码,因为它很难阅读。我会留给你决定,但这绝对不会让你无意中在条件中分配一个值,因为你不能将值赋给1000。

1

变化:

if (TestThis=1000) 

要:

if (TestThis==1000) 

你实际上是分配给TestThis将返回true,执行条件块。

3

在if语句,你设置TestThis1000,而不是比较1000=运算符返回设置的值,其值为true,因为它不是undefined0null。您只需使用==运算符。

if(TestThis == 1000)