看板 Ajax 關於我們 聯絡資訊
各位版上的大神們好,想請問各位: let age = 27; age.toString(); if (age===27) { console.log("number"); } else if (age==="27") { console.log("string"); } else { console.log("I don't know."); } 這個例子中,結果會是『number』,因為 age 是 number,只有 age.toString 是 string 對嗎? 第二個例子: let friends = ["John", "Sandy", "Alex", "Jim", "Greg"]; let friends = ["John", "Sandy", "Alex", "Jim", "Greg"]; friends.push("Harry"); console.log(friends); 這個例子中,結果會是["John", "Sandy", "Alex", "Jim", "Greg", "Harry"] 但,為什麼第一個例子中 age 使用了 .toString() 後,『age』 本身並沒有變成 string;但在第二個例子中,friends 使用了 .push("Harry") 後,『friends』本身卻改變了? 感謝各位! -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 42.76.156.60 (臺灣) ※ 文章網址: https://www.ptt.cc/bbs/Ajax/M.1655571371.A.462.html
kyrc: https://mzl.la/3ybX6zL06/19 01:42
kyrc: age = age.toString();06/19 01:43
※ 編輯: d13751200344 (123.205.120.144 臺灣), 06/19/2022 02:51:48
BugofBook: 因為number是不可變的,而push不是不可變的method 06/19 10:03
usagi719: 簡單講,沒有為什麼,原始函式就這麼寫。複雜講,這跟 06/19 22:20
usagi719: 程序員的哲學美學有關。js主推純函式美學,但以前沒有 06/19 22:20
usagi719: ,現在框架array操作方法就會寫immutable的,禁止直接 06/19 22:20
usagi719: 改變array而是return新的array,js有特別優化,使得程 06/19 22:20
usagi719: 式更穩定效率。能用const就用,少用變數 06/19 22:20
ck574b027: 會對side effect函數設計命名慣例的嚴謹語言本來就不多 06/20 03:14
laechan: 你只能習慣有些就是這樣,有些就是那樣(如 array.sort() ) 06/20 17:01
laechan: 不想記就是寫code時多花一些時間在debug 06/20 17:02
laechan: 我是更懶連push是啥平常都沒記,要用時google就好了 06/20 17:03
laechan: 像VB是Cint/Cstr,到javascript變 parseInt/toString = = 06/20 17:03
laechan: 若你常寫常用則自然會知道啥時要用 變數=xxx, 啥時不用 06/20 17:04
ck574b027: 不是吧,在ide看回傳type不就好了 06/21 03:49
Haneki: string 跟 array 不一樣喔~ 一個是primitive type一個是re 06/25 12:40
Haneki: ference type 06/25 12:41