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

        }
    }
}
4

5 回答 5

7

您在 if 条件检查中为变量赋值。您的TestThis变量被赋值为 1000,在被 JavaScript 转换为布尔值后将为真。这就是为什么你的函数总是被执行的原因。您可以在此处阅读有关自动类型转换的更多信息。

现在要修复您的代码,请更改此 -

if (TestThis=1000)

对此——

if (TestThis == 1000)

或者如果您不想要自动类型转换 -

if (TestThis === 1000)

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

if (1000 === TestThis)

这被称为尤达条件(是的,以绝地大师尤达命名)。这样做的好处是,如果有人错误地只设置了一个等号,则会导致错误,因为您无法将任何内容分配给常量。不过,我从未亲自使用过它(而且可能永远不会,因为我觉得它相当不合常规)。

于 2013-08-30T18:44:55.773 回答
4

JavaScript 允许您在条件中分配一个值,因此这将TestThis=1000导致 1000 并且在条件语句中正数(实际上不是 0)导致评估为真。

要使其成为条件,您应该这样做TestThis===1000(并且您应该几乎总是使用===over the==作为===强制两者的实际比较,并且不要尝试将条件的一部分转换为等于另一部分。)

你也可以这样做1000 === TestThis(或相反1000 == TestThis)有人说这是不好的编码,因为它很难阅读。我将由您决定,但这绝对不会让您意外地在条件中分配一个值,因为您不能将值分配给 1000。

于 2013-08-30T18:46:01.060 回答
3

在 if 语句中,您设置 TestThis1000,而不是其与1000. 该=运算符返回设置的值,该值的计算结果为 true,因为它不是undefined0null。您只需要使用==运算符。

if(TestThis == 1000)
于 2013-08-30T18:47:59.957 回答
1
if (TestThis == 1000)

改成这样。

如果你必须有比较平等==

于 2013-08-30T18:45:59.133 回答
1

改变:

if (TestThis=1000)

至:

if (TestThis==1000)

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

于 2013-08-30T18:46:54.807 回答