簡體   English   中英

JavaScript 使用三元運算符減少

[英]JavaScript reduce with ternary operator

我有一段可以正常工作的代碼。 此代碼查找數字數組中的最大值。 有人可以將它翻譯成簡單的 JavaScript(沒有三元),以便新手程序員可以理解它嗎?

  const mostVotes = votes.reduce((bestIndex, v, i, arr) => v > arr[bestIndex] ? i : bestIndex, 0);

起初,我試圖實現 Math.max,但我需要數組中最大值的索引,所以我采用了 reduce,這就是我試圖用它來做的。

const mostVotes = votes.reduce((acc, value, i, arr) => {
  if(value > acc) {
    return i
  }
}, 0)

感謝您的回答,非常感謝! 我開始明白這一點,現在更清楚了。 Javascript reduce 和三元結合在一起是一個很好的選擇。

本質上,您提供的代碼是循環遍歷votes每個元素並檢查它是否大於存儲在特定索引處的元素。 該索引存儲在變量bestIndex ,用於標記/跟蹤索引,該索引包含循環時看到的所有元素中的最大元素。

在您的示例中,您的三元正在檢查給定元素是否大於當前標記的最大元素(通過執行v > arr[bestIndex] )。 如果是這種情況,我們將當前元素的索引設置為最大元素的新位置(通過隱式返回i )。 如果不是這種情況,我們通過隱式返回bestIndex保留最大元素的索引。

您可以通過使用 for 循環和 if 語句將其轉換為更程序化的編程風格,如下所示:

 let votes = [-4, 10, 100, -3, 40]; let positionOfMax = 0; for(let i = 0; i < votes.length; i++) { if(votes[i] > votes[positionOfMax]) { // v > arr[bestIndex] positionOfMax = i; // ? i (from ternary) } /* Not needed else {posittionOfMax = positionOfMax} // : bestIndex (from ternary) */ } console.log(positionOfMax);

我鼓勵您查看.reduce()和有關條件(三元)運算符的文檔。 它們都是有用且強大的工具,可以幫助您加快開發速度。

原始代碼可能令人困惑的是缺少括號{}

() => 'test'() => { return 'test' }

在你的情況下:

(bestIndex, v, i, arr) => v > arr[bestIndex] ? i : bestIndex

(bestIndex, v, i, arr) => {
  return (v > arr[bestIndex] ? i : bestIndex)
}

(bestIndex, v, i, arr) => {
  if(v > arr[bestIndex])
    return i
  else 
    return bestIndex
}

const mostVotes = votes.reduce((bestIndex, v, i, arr) => {
  if(v > arr[bestIndex])
    return i
  else 
    return bestIndex
}, 0);

下面的if/else應該能讓你到達你想去的地方。

if (v > arr[bestIndex]) {
  return i
} else {
  return bestIndex
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM