选择排序算法仅在传递不带 0 的数组时有效

Selection sort algorithm only works when an array without 0 is passed

我正在尝试实现选择排序算法。出于某种原因,它仅在我传递一个不包含值 0 的数组时才有效。我似乎无法弄清楚为什么要这样做。

这是我的解决方案:

function selectionSort(array) {
  let smallestItem = null;
  let smallestItemIndex = null;
  for(i = 0 ; i < array.length ; i++){
    smallestItemIndex = i;
    for(j = i + 1 ; j < array.length ; j++){
      if(array[smallestItemIndex] > array[j]){
        smallestItem = array[j];
        smallestItemIndex = j;
      } 
    }
    if(smallestItem){
      let temp = array[i];
      array[i] = smallestItem;
      array[smallestItemIndex] = temp;
    }
    smallestItem = null;
  }

发生这种情况是因为在 JS 检查中:if(smallestItem){ 对 0 和 null 都将 return 为真 - 如果最小项是0.

要修复它切换到 if(smallestItem == null){