作者d13751200344 (三更灯火五更鸡)
看板Ajax
标题[问题] 初学JavaScript问题
时间Sun Jun 19 00:56:07 2022
各位版上的大神们好,想请问各位:
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://webptt.com/cn.aspx?n=bbs/Ajax/M.1655571371.A.462.html
2F:→ kyrc: age = age.toString();06/19 01:43
※ 编辑: d13751200344 (123.205.120.144 台湾), 06/19/2022 02:51:48
3F:→ BugofBook: 因为number是不可变的,而push不是不可变的method 06/19 10:03
4F:→ usagi719: 简单讲,没有为什麽,原始函式就这麽写。复杂讲,这跟 06/19 22:20
5F:→ usagi719: 程序员的哲学美学有关。js主推纯函式美学,但以前没有 06/19 22:20
6F:→ usagi719: ,现在框架array操作方法就会写immutable的,禁止直接 06/19 22:20
7F:→ usagi719: 改变array而是return新的array,js有特别优化,使得程 06/19 22:20
8F:→ usagi719: 式更稳定效率。能用const就用,少用变数 06/19 22:20
9F:→ ck574b027: 会对side effect函数设计命名惯例的严谨语言本来就不多 06/20 03:14
10F:→ laechan: 你只能习惯有些就是这样,有些就是那样(如 array.sort() ) 06/20 17:01
11F:→ laechan: 不想记就是写code时多花一些时间在debug 06/20 17:02
12F:→ laechan: 我是更懒连push是啥平常都没记,要用时google就好了 06/20 17:03
13F:→ laechan: 像VB是Cint/Cstr,到javascript变 parseInt/toString = = 06/20 17:03
14F:→ laechan: 若你常写常用则自然会知道啥时要用 变数=xxx, 啥时不用 06/20 17:04
15F:→ ck574b027: 不是吧,在ide看回传type不就好了 06/21 03:49
16F:推 Haneki: string 跟 array 不一样喔~ 一个是primitive type一个是re 06/25 12:40
17F:→ Haneki: ference type 06/25 12:41