我有以下代碼:獲取試圖推到一個數組時的錯誤消息
if (typeof $scope.grid.data == 'undefined') {
$scope.grid.data = [];
}
$scope.grid.data.push(result);
我把支票未定義的,但我還是從推說收到錯誤消息:
TypeError: Cannot call method 'push' of null
任何建議,將不勝感激
我有以下代碼:獲取試圖推到一個數組時的錯誤消息
if (typeof $scope.grid.data == 'undefined') {
$scope.grid.data = [];
}
$scope.grid.data.push(result);
我把支票未定義的,但我還是從推說收到錯誤消息:
TypeError: Cannot call method 'push' of null
任何建議,將不勝感激
我一直是細跟的簡單:
if (!$scope.grid.data) {
$scope.grid.data = [];
}
這應該在兩種情況下都能捕獲它(null & undefined)。
作爲錯誤消息顯示,所討論的對象是null
,不undefined
。這兩個是不同的值,你檢查的方式只會檢查未定義的。檢查是否一個對象,最好的辦法是undefined
或null
是利用一個事實,即null
和undefined
相互之間的隱式轉換,並且做到:
if ($scope.grid.data == null) {
幾個例子示出該在http://jsfiddle.net/5kdG8/和http://jsfiddle.net/kxGJU/ – tvanfosson