2016-11-17 6 views
1
$scope.input.opening_hours = place.opening_hours && place.opening_hours.weekday_text ? place.opening_hours.weekday_text : ''; 

Uncaught TypeError: Cannot read property 'weekday_text' of undefined(…)JavaScriptの三元のx &&

if (place.opening_hours && place.opening_hours.weekday_text) { 
    $scope.input.opening_hours = place.opening_hours.weekday_text; 
} else { 
    $scope.input.opening_hours = ''; 
} 

他のyの場合、私は、ステートメント場合は、この三元バージョンを作成しようとしていますが、私は上記のエラーを取得します。これを簡単なステートメントに単純化する最良の方法は何ですか?

+1

opening_hours私は演算子の優先順位は、あなたが期待するものとは異なり、あなたが実際に実行していると思う未定義 – Mahi

+2

です:? $ scope.input.opening_hours = place.opening_hours &&(place.opening_hours.weekday_text place.opening_hours.weekday_text : '';) –

+2

カッコを使用します。しかし、なぜあなたはそのタスクを作る必要があるのか​​分かりませんが、元の 'if()'を読みやすくしています。 –

答えて

-1

私はコメントであなたを伝えると、あなたは括弧を追加する必要があります。

$scope.input.opening_hours = (place.opening_hours && place.opening_hours.weekday_text) ? place.opening_hours.weekday_text : ''; 

をそして、あなたが改善することができます。

$scope.input.opening_hours = ((place.opening_hours && place.opening_hours.weekday_text) ? place.opening_hours.weekday_text : ''); 

後者は、内側の括弧がすべて前に実行されることを保証します。それは数学のように、内側の括弧は外側の括弧の前に実行する必要があります。

2

あなたは三項演算子を必要としない、これはうまくやる:おそらくさえ

... = place.opening_hours && place.opening_hours.weekday_text || ''; 

を:

... = (place.opening_hours || {}).weekday_text || ''; 

は、三元表現が働いているべきであると言って、どうしてそんなことはしないのか分からない。 AngularJSで

0

if (angular.isObject(place) && place.hasOwnProperty('opening_hours')) { 
    var openingHours = place.opening_hours; 
    if (angular.isObject(openingHours) && openingHours.hasOwnProperty('weekday_text')) { 
     $scope.input.opening_hours = openingHours.weekday_text; 
    } 
    else { 
     $scope.input.opening_hours = ''; 
    } 
} 
else { 
    $scope.input.opening_hours = ''; 
} 

純粋JSで:

// check if a object value 
function isObject (_object) { 
    return Object.keys(_object).length >= 0 && _object.constructor === Object 
} 

if (isObject(place) && place.hasOwnProperty('opening_hours')) { 
    var openingHours = place.opening_hours; 
    if (isObject(openingHours) && openingHours.hasOwnProperty('weekday_text')) { 
     $scope.input.opening_hours = openingHours.weekday_text; 
    } 
    else { 
     $scope.input.opening_hours = ''; 
    } 
} 
else { 
    $scope.input.opening_hours = ''; 
} 

pathExists JS(基本)を使用して:三元

if (objectPathExists(place, 'opening_hours.weekday_text')) { 
    $scope.input.opening_hours = openingHours.weekday_text; 
} else { 
    $scope.input.opening_hours = ''; 
} 

$scope.input.opening_hours = objectPathExists(place, 'opening_hours.weekday_text') ? openingHours.weekday_text : '' 

pathExists JS(試作品)の使用:

if (place.pathExists('opening_hours.weekday_text')) { 
    $scope.input.opening_hours = openingHours.weekday_text; 
} else { 
    $scope.input.opening_hours = ''; 
} 

は三元:

$scope.input.opening_hours = place.pathExists('opening_hours.weekday_text') ? openingHours.weekday_text : ''