2016-11-17 1 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(…)자바 스크립트 삼항 경우 X && 다른

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

내가 if 문이의 원 버전을 만들려고 노력하고 있지만 위의 오류가 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 (프로토 타입)을 사용하여 53,691,363,210

:

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 : '' 
관련 문제