JavaScript - 逗號運算子



JavaScript 逗號運算子

在 JavaScript 中,**逗號**運算子 (,) 從左到右計算多個表示式。您可以使用左側表示式的結果值作為右側表示式的輸入。計算完所有表示式後,它將返回最右側表示式的結果值。

但是,逗號運算子也用於 'for' 迴圈、陣列、物件等。在本節中,您將學習逗號運算子的所有用例。

語法

您應該遵循以下語法來使用逗號表示式計算多個表示式。

var answer = (exp1, exp2, exp3, ex4, ...);

返回值

它只返回最後一個表示式的結果值。

示例

讓我們透過一些示例詳細瞭解 JavaScript 逗號運算子。

示例:帶字串的逗號運算子

在下面的示例中,我們在括號中添加了 4 個逗號分隔的字串。這裡,每個字串都作為一個表示式。程式碼將計算字串並返回最後一個字串。在輸出中,您可以看到它列印了 'CSS',因為它是最右邊的字串。

<html>
<body>
    <p id = "output"> </p>
    <script>
        let output = document.getElementById("output");
        let ans = ("JavaScript", "Python", "HTML", "CSS");
        output.innerHTML = "The value of the ans variable is: " + ans;
    </script>
</body>
</html>

示例:帶表示式的逗號運算子

在下面的示例中,我們定義了變數 'a' 並將其初始化為 5。在 'ans' 變數中,我們儲存逗號運算子返回的結果值。第一個表示式將 a 的值更新為 8,第二個表示式將 a 的值加 1,第三個表示式將 2 加到變數 'a' 的更新值上。

'ans' 的值為 11,這是逗號運算子最右側表示式返回的值。

<html>
<body>
    <p id = "output"> </p>
    <script>
        let output = document.getElementById("output");
        let a = 5;
        let ans = (a = 8, a++, a += 2);
        output.innerHTML = "The value of the ans variable is: " + ans;
    </script>
</body>
</html>

示例:帶函式的逗號運算子

在下面的示例中,我們定義了 first() 和 second() 函式。它還會根據函式名稱列印訊息並從函式返回該值。

我們使用逗號運算子來執行多個函式。在輸出中,您可以看到它呼叫了兩個函式,但只打印了 second() 函式的返回值。

<html>
<body>
    <p id="output"> </p>
    <script>
        let output = document.getElementById("output");
        function first() {
            output.innerHTML += "The first function is called! <br/>";
            return 1;
        }

        function second() {
            output.innerHTML += "The second function is called! <br/>";
            return 2;
        }

        let ans = (first(), second());
        output.innerHTML += "The value of the ans variable is: " + ans;
    </script>
</body>
</html>

逗號運算子的其他用例

用於在一行中定義多個變數。

let m = 1, n = 2, x = 3;

用於使用多個元素初始化陣列。

const arr = [10, 20, 30, 40, 50, 60];

用於使用多個屬性定義物件。

const obj = {
   name: "tutorialspoint",
   age: 10,
   ... other properties
}

您可以使用逗號運算子在 for 迴圈中初始化或更新多個變數。

for(let p = 0, q = 1; p < n; p++, q++) {
 // Code for the loop
}

用於將多個引數傳遞到函式中。

function func(param1, param2, ... ) {  
 // function code
 }

OR
func(10, 20, 30, ...);

用於匯入或匯出。

import { func2, variable } from './module2.js';
OR
export {func1, variable, num};

用於解構陣列或物件。

let [a, b, c] = [34, 72, 23]; 

用於在控制檯中列印多個變數。

console.log(a, b, c) // a, b, and c are variables.
廣告