2026-02-10 js入门
原来我是打算看<< head first JavaScript>>的,但发现他确实是在把我当智障教,而且内容太老了,根本看不下去,于是就选了javascript.info来看.
基本语法
数据类型
js和python一样是动态类型语言,故可以有:
1 | // 没有错误 |
number and BigInt
int和float统一称为number.
除了常规的数字,还包括所谓的“特殊数值(“special numeric values”)”也属于这种类型:Infinity、-Infinity 和 NaN(计算错误).
由于number类型无法安全表示大于9007199254740991的整数,故后来又发明了BigInt用来安全表示任意长度的整数,通过将 n 附加到整数字段的末尾就可以创建BigInt.
1 | // 尾部的 "n" 表示这是一个 BigInt 类型 |
string
三种引号:
- 双引号:
"Hello". - 单引号:
'Hello'. - 反引号:
Hello.
反引号用于将变量嵌入字符串
eg
1 | let name = "John"; |
- 只有`可以表示多行字符串,用单双引号跨行表示字符串都会直接报错
- 主流静态语言都不允许字符串跨行,不过一般静态语言也用不上那么长的字符串
null and undefined
null指代未知值或空值,而undefined指代未被赋值的值.
1 | let age = null; |
Interaction: alert, prompt, confirm
alert('hello,world')
The mini-window with the message is called a modal window. The word “modal” means that the visitor can’t interact with the rest of the page, press other buttons, etc, until they have dealt with the window. In this case – until they press “OK”.
result = prompt(title, [default]);
The function prompt accepts two arguments:
- title
- The text to show the visitor.
- default
- An optional second parameter, the initial value for the input field.
prompt 将返回用户在 input 框内输入的文本,默认为string,如果用户取消了输入,则返回 null,与python中的input()类似
result = confirm(question);
显示信息等待用户点击确定或取消。点击确定返回 true,点击取消或按下 Esc 键返回 false。
1 | let isBoss = confirm("Are you the boss?"); |
上述所有方法共有两个限制:
- 模态窗口的确切位置由浏览器决定。通常在页面中心。
- 窗口的确切外观也取决于浏览器。我们不能修改它。
function
函数声明与函数表达式
1 | function showMessage() { |
下列方法称为函数表达式
1 | let sayHi = function() { |
还可以这样写
1 | function sayHi() { // (1) 创建 |
也就是说可以把函数看作一个变量
回调函数与匿名函数
1 | function ask(question, yes, no) { |
这里两个函数没有名字,故称为匿名函数,同时两个函数作为传入参数,可称为回调函数(callback).
箭头函数
1 | let sum = (a, b) => a + b; |
1 | let sum = (a, b) => { // 花括号表示开始一个多行函数 |
注释
- 在该注释的地方注释,在不需要注释的地方则不注释,甚至写得好的自描述函数本身就是一种注释
- “如果代码不够清晰以至于需要一个注释,那么或许它应该被重写。”
falsy and truthy
falsy只有以下几种:
1 | 0, -0, "", null, undefined, NaN, false |
在诸如if(i)这样的判断句中只有i为falsy才会不执行
对象
属性中的[]与.
js中的.与python中基本相同,可以用于在对象之外添加普通属性,访问属性,更改属性,但js中还有特殊运算符[],可以用于命名特殊属性,将普通变量变成属性.
任意表达式
1 | let key = "likes birds"; |
计算属性
1 | let fruit = prompt("Which fruit to buy?", "apple"); |
属性值简写
1 | function makeUser(name, age) { |
对象方法
1 | // 这些对象作用一样 |
也就是说有两种方式可以声明js对象方法
New的使用
1 | function User(name) { |
其中new User()做了类似以下描述的事情
1 | function User(name) { |
Class
js中的class是后添加的特性,实际上是一种语法糖
1 | class Person { |
export与import
export与import可以看作是python中的模块导入,区别是只有用export标记的函数和变量才可以在其他文件中导入,导入方式也与python类似
eg
/project
├─ math.js
└─ main.js
1 | //math.js |
1 | //main.js |
小总结(2/20)
事实上看了这么久js.info我已经觉得很烦了,因为js的语法混乱不堪,有很多没意义的历史残留,而教程有时候讲的过于抽象和笼统,有时候又讲的十分细致和琐碎,不过通过反刍还是大概能看清楚js的基本用法的,至于其他的章节匆匆速览一遍就不想再看了,接下来我应该要直接上手next.js来试试深浅.






