Javascript if variable is undefined then use another
This question already has an answer here:
I want to leave short comment but now I understand that will be better if I explain.
var job = $scope.job || $scope.jobs;
undefined == false; // prints true
So that's how it works.
If $scope.job == undefined == false || $scope.jobs == {...} == true.
If job will be undefined - it will be false so or
operand returns true value.
So if i understand what you mean:
if ($scope.job)
var job = $scope.job;
else
{
var job = $scope.jobs;
$scope.job = $scope.jobs;
}
well, shorthand then:
var job = $scope.job = $scope.job || $scope.jobs;
Or you can use ternary operator
var job = $scope.job ? $scope.job : $scope.jobs
or
var job = $scope.job == undefined ? $scope.job : $scope.jobs
链接地址: http://www.djcxy.com/p/73362.html