X++ & ++X 差別與其中的涵義
周柏諭 BO-YU CHOU
Posted on August 19, 2022
前言
在學習閉包時看到一段程式碼的輸出覺得不解:
function aFunc(x){
function bFunc(){
console.log( x++ )
}
return bFunc
}
const newFunc = aFunc(1)
newFunc()
newFunc()
output:
- 1
- 2
為啥不是輸出 2和3呢?
查了一下x++這個看過無數次的語法後,才發現對他有多不熟悉,
++x increments the value of x and then returns x
x++ returns the value of x and then increments
原來 x++代表 先返回 x 再x+1
假如 x是 3,那 ++x 將把 x 設定為 4 並回傳 4,而 x++ 會回傳 3 , 接著才把 x 設定為 4。
完整點的例子:
var x = 5;
console.log( x++ ) // output x=5
console.log (x) //output x=6
console.log(++x) //output x=7
console.log(x) //output x=7
參考文章:
https://www.sololearn.com/Discuss/727179/x-x-i-cant-understand-it
https://developer.mozilla.org/zh-TW/docs/Web/JavaScript/Guide/Expressions_and_Operators
💖 💪 🙅 🚩
周柏諭 BO-YU CHOU
Posted on August 19, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
react Axios NPM Package: A Beginner's Guide to Installing and Making HTTP Requests
November 30, 2024