[英]Understanding Javascript return statement
我已經看到了下面的代碼,並且不太確定發生了什么。 函數中沒有設置返回類型,因此我無法弄清楚ORing 3字符串會做什么。 該方法將返回什么,或執行什么操作?
return $scope.filterLabels[key] ||
$scope.filterLabels[oldSchoolFacetCode()] ||
key;
||
如果為真,運算符將返回左參數,否則返回右參數。
例如, null || false
null || false
計算為false
,而false || null
false || null
為null
。
考慮到這一點, return
語句將返回:
$scope.filterLabels[key]
如果是真的 $scope.filterLabels[oldSchoolFacetCode()]
如果第一個是虛假的,這是真的 key
。 該代碼實際上是:
if( $scope.filterLabels[key]) return $scope.filterLabels[key];
if( $scope.filterLabels[oldSchoolFacetCode()]) return $scope.filterLabels[oldSchoolFacetCode()];
return key;
如果操作數在||的左側 操作數是真實的,它將返回該操作數(左側),如果錯誤,則將返回右側操作數。
一個更簡單的方案就是這樣。
return true || false; // this would return true
return false || true; // this would also return true
return false || 3; // this would return 3
return 3 || 7; // this would also return 3
在這種情況下,這意味着...
return a || b || c;
如果a為true,它將返回true。
如果a為假,則將評估下一個表達式,即。
虛假的價值觀:
false
0
(零) ""
或''
(空字符串) null
undefined
NaN
(非數字) 如果任何一項為真,|| 運算符將返回評估為true的第一項(==不是===)
return "" || "foo" || "bar"
返回“ foo”
上面的語句將返回一個有效值,表示不是null
/ defined等。它將從左到右進行驗證。
考慮這種情況,
return a || b || c;
現在,如果a
和b
undefined
,則在這種情況下它將返回c
的值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.