2014-01-14 40 views
0

我有以下代碼:我試圖檢查未定義的,但它不工作

$scope.$watch("pid", _.debounce(function (pid) { 

    var a = pid; 

    $scope.$apply(function (pid) { 
     if (typeof pid == "undefined" || pid == null || pid === "") { 
      $scope.pidLower = null; 
      $scope.pidUpper = null; 
     } 
     else if (pid.indexOf("-") > 0) { 
      pid = pid.split("-"); 
      $scope.pidLower = parseInt(pid[0]); 
      $scope.pidUpper = parseInt(pid[1]); 
     } 
     else { 
      $scope.pidLower = parseInt(pid); 
      $scope.pidUpper = null; 
     } 
    }); 
}, 1000)); 

的第一次代碼運行時(PID字段爲空),我檢查PID與谷歌的開發工具它顯示爲「未定義」。但是,當代碼運行時,它不會進入第一個條件。相反,它進入到第二,並給出一個錯誤說:

類型錯誤:對象#有沒有方法「的indexOf」

誰能告訴我,爲什麼它忽略了第一個if語句?

這裏是我所得到的,當我使用控制檯檢查第一行PID與if:

console.log(typeof pid) 
object 
undefined 
+0

如果它未定義,那麼它應該進入第一個條件。試着製作一個*完整*簡化的測試用例,以便我們看到問題所在。 – Quentin

+1

從看到錯誤信息並進入第二個條件,我會認爲它是實際定義的,但沒有'indexOf'方法(表示它不是一個字符串或數組)。在devtools中檢查變量時,你確定你在正確的範圍內嗎?你可以'console.log(typeof pid)'? – SoonDead

+0

@SoonDead - 我做了控制檯日誌並更新了問題。 – Melina

回答

1

Here is what I get when I use the console to check pid on the first line with an if:

console.log(typeof pid) 
object 
undefined 

這是說的類型的pid是對象。它然後console.log()的返回值是undefined

它不會進入第一個if,因爲該變量不是,如您所想,未定義。

然後它失敗,因爲無論對象是什麼類型pid是,它不是一個與indexOf方法。

-1

試試這個:

if (!pid) { 
       $scope.pidLower = null; 
       $scope.pidUpper = null; 
      } 
      else if (pid.indexOf("-") > 0) { 
       pid = pid.split("-"); 
       $scope.pidLower = parseInt(pid[0]); 
       $scope.pidUpper = parseInt(pid[1]); 
      } 
      else { 
       $scope.pidLower = parseInt(pid); 
       $scope.pidUpper = null; 
      } 
相關問題