[問題] 初學JavaScript問題

看板Ajax作者 (三更燈火五更雞)時間1年前 (2022/06/19 00:56), 1年前編輯推噓1(1016)
留言17則, 6人參與, 1年前最新討論串1/1
各位版上的大神們好,想請問各位: 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

06/19 01:42, 1年前 , 1F
06/19 01:42, 1F

06/19 01:43, 1年前 , 2F
age = age.toString();
06/19 01:43, 2F
※ 編輯: d13751200344 (123.205.120.144 臺灣), 06/19/2022 02:51:48

06/19 10:03, 1年前 , 3F
因為number是不可變的,而push不是不可變的method
06/19 10:03, 3F

06/19 22:20, 1年前 , 4F
簡單講,沒有為什麼,原始函式就這麼寫。複雜講,這跟
06/19 22:20, 4F

06/19 22:20, 1年前 , 5F
程序員的哲學美學有關。js主推純函式美學,但以前沒有
06/19 22:20, 5F

06/19 22:20, 1年前 , 6F
,現在框架array操作方法就會寫immutable的,禁止直接
06/19 22:20, 6F

06/19 22:20, 1年前 , 7F
改變array而是return新的array,js有特別優化,使得程
06/19 22:20, 7F

06/19 22:20, 1年前 , 8F
式更穩定效率。能用const就用,少用變數
06/19 22:20, 8F

06/20 03:14, 1年前 , 9F
會對side effect函數設計命名慣例的嚴謹語言本來就不多
06/20 03:14, 9F

06/20 17:01, 1年前 , 10F
你只能習慣有些就是這樣,有些就是那樣(如 array.sort() )
06/20 17:01, 10F

06/20 17:02, 1年前 , 11F
不想記就是寫code時多花一些時間在debug
06/20 17:02, 11F

06/20 17:03, 1年前 , 12F
我是更懶連push是啥平常都沒記,要用時google就好了
06/20 17:03, 12F

06/20 17:03, 1年前 , 13F
像VB是Cint/Cstr,到javascript變 parseInt/toString = =
06/20 17:03, 13F

06/20 17:04, 1年前 , 14F
若你常寫常用則自然會知道啥時要用 變數=xxx, 啥時不用
06/20 17:04, 14F

06/21 03:49, 1年前 , 15F
不是吧,在ide看回傳type不就好了
06/21 03:49, 15F

06/25 12:40, 1年前 , 16F
string 跟 array 不一樣喔~ 一個是primitive type一個是re
06/25 12:40, 16F

06/25 12:41, 1年前 , 17F
ference type
06/25 12:41, 17F
文章代碼(AID): #1YhWEhHY (Ajax)
文章代碼(AID): #1YhWEhHY (Ajax)