比较运算符
<
>
<=
>=
==
(会进行隐式类型转换)!=
===
(不会进行隐式类型转换)!==
隐式类型转换🍭
针对不相同的类型进行比较 / 运算时, 将其尽可能的转换为相同的类型
举个栗子🌰
针对如下代码
由于其类型不同, 默认比较结果为 false
但是==
触发了隐式类型转换(将其尽可能转换为相同的类型)
导致其结果为 true
let a = 10; let b = '10'; console.log(a == b); let c = true; let d = 1; console.log(c == d);
若使用===
(不进行隐式类型转换), 其结果为 false
- "强类型"语言: 不太支持隐式类型转换
- "弱类型"语言: 比较支持隐式类型转换
默认强类型语言比弱类型语言好
(类型强, 即不同类型之间的区分度较高 → 编译器能做的检查工作就更多 → 代码的出错概率就更低)
逻辑运算符
&&
||
!
位运算
&
|
~
^
移位运算
<<
>>
>>>
🔎数组
在 JS 中
数组不仅仅是传统意义上的数组
而是具有"键值对"性质的数组
创建数组
let arr = new Array();
(通过 new 创建)let arr = [];
(直接创建)
在 JS 中, 数组的元素可以是任意类型
举个栗子🌰
let arr = [1, 'hello', true, []]
获取数组中的元素
创建一个数组let arr = ['hello', 'the', 'world'];
获取数组中的指定元素🍭
根据下标获取指定元素
例如
console.log(arr[0]);
console.log(arr[1]);
console.log(arr[2]);
特殊的下标🍂
以let arr = ['hello', 'the', 'world'];
为例
arr 的长度为 3
默认下标从 0 开始
在 JS 中, 存在一些特殊的下标
> 数组长度的下标
(空余位置为 empty)< 0 的下标
(解析为键值对结构)自定义的下标
(解析为键值对结构)
> 数组长度的下标
(空余位置为 empty)
let arr = ['hello', 'the', 'world']; arr[100] = '滑稽'; console.log(arr);
< 0 的下标
(解析为键值对结构)
let arr = ['hello', 'the', 'world']; arr[-1] = 'Tom'; arr[-2] = 'Homo'; console.log(arr);
自定义的下标
(解析为键值对结构)
let arr = ['hello', 'the', 'world']; arr['name'] = 'Jack'; console.log(arr);
获取数组中的所有元素🍭
- 利用循环获取数组中所有元素
- 利用数组名获取数组中所有元素
利用循环获取数组中所有元素🍂
方法1
for(let i = 0; i < arr.length; i++) { console.log(arr[i]); }
方法2
for(let i in arr) { console.log(arr[i]); }
方法3
for(let i of arr) { console.log(i); }
注意区分let i in arr
与let i of arr
in
表示数组的下标
of
表示数组的元素
运行效果
利用数组名获取数组中所有元素🍂
console.log(arr);
运行效果
添加数组中的元素
利用push
添加数组中的元素
举个栗子🌰
let arr = ['hello', 'the', 'world'];
添加元素
arr.push('bibubibu');
运行效果
删除数组中的元素
利用splice
删除数组中的元素
splice
一共 3 个参数
start
(必需), 指定要操作的起始位置deleteCount
(可省略), 从起始位置开始要删除的元素数量. 若省略或值大于从起始位置到数组末尾的元素数量时, 则删除从起始位置到数组末尾的所有元素item1, item2, ...
(可省略), 要添加到数组的元素, 从起始位置添加
删除数组中的元素🍭
let arr = ['hello', 'the', 'world']; // 删除 arr.splice(2, 1); // ['hello', 'the'
添加数组中的元素🍭
let arr = ['hello', 'the', 'world']; // 添加 arr.splice(2, 0, 'bibubibu'); // ['hello', 'the', 'bibubibu', 'world']
替换数组中的元素🍭
let arr = ['hello', 'the', 'world']; // 替换 arr.splice(2, 1, 'bibubibu'); // ['hello', 'the', 'bibubibu']
🔎函数
语法
function 函数名(形参列表) { 函数体 return 返回值; // 可省略 }
举个栗子🌰
function add(x, y) { console.log(x + y); return x + y; }
注意🍂
- 形参无需指定类型
- NaN, Not a Number
- 实参个数 < 形参个数, 多出来的形参的值为 undefined
- 实参个数 > 形参个数, 多出来的实参不参与运算
实参个数 < 形参个数🍭
function add(x, y) { return x + y; } console.log(add(10)); console.log(add('10'));
实参个数 > 形参个数🍭
function add(x, y) { return x + y; } console.log(add(10, 20, 30)); console.log(add(20, 30, 40));
实参个数较多时, 如何获取
通过 arguments 获取全部实参
每个函数都会自定义一个 arguments 变量, 是一个数组, 包含全部实参
function add() { let ret = 0; for(let x of arguments) { ret += x; } return ret; } console.log(add(10, 20, 30, 40));