简体   繁体   中英

How can I check if an array is set and contains a value at the same time?

I need to check if ['pk'] is available in the first item in an array, and only then do some stuff. The array is not always populated, so I am ending up with a block of code that feels a little bit bloated.

How can I make this code shorter and nicer? I'm sure Javascript have a way to do this better... (without having a lot of errors in the console while the array is empty...)

var $selectedItem = $scope.selectedItem[0] || null;
if($selectedItem) {
  var $selectedPK = $selectedItem['pk'];
}
if($selectedPK) { ... }

Since there's no further checking if the first part of the boolean and condition is false , this is much more concise:

if ($selectedItem && $selectedItem['pk']) {
  ...
}

I think you should be able to make the assignment in the condition right away:

if ($selectedItem && ($selectedPk = $selectedItem['pk'])) {
  ...
}

Sounds like you could at least combine the two

var $selectedItem = $scope.selectedItem[0] || null;
if($selectedItem) {
  var $selectedPK = $selectedItem['pk'];
  if($selectedPK) { 
    ... 
  }
}

Here's one more ;)....

if ($scope.selectedItem[0] && $scope.selectedItem[0].pk!==undefined) {
 // do stuff
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM