JavaScript(基础)
海边的小溪鱼 2021-06-24 ES6
从入门到放弃
# 数据类型检测
# 1. typeof():基本数据类型检测
- 注意:只适用于检测基本类型的数据,检测数组/对象(复杂数据类型)时都返回 object
// 写法1
typeof(10) // number
typeof("hello") // string
typeof(true) // boolean
// 写法2
var num = 10;
typeof num // number
1
2
3
4
5
6
7
2
3
4
5
6
7
# 2. Object.prototype.toString.call():检测所有类型
- 适用于判断 基本数据类型 或 JavaScript 内置对象
var num = 10
var arr = ["age", 18]
var arr1 = new Array()
var obj = { name: "jack" }
// 基本上所有的类型都可以通过这个方法检测
console.log(Object.prototype.toString.call(num)); // [object Number]
console.log(Object.prototype.toString.call(arr)); // [object Array]
console.log(Object.prototype.toString.call(arr1)); // [object Array]
console.log(Object.prototype.toString.call(obj)); // [object Object]
console.log(Object.prototype.toString.call(null)); // [object Null]
console.log(Object.prototype.toString.call(true)); // [object Boolean]
1
2
3
4
5
6
7
8
9
10
11
2
3
4
5
6
7
8
9
10
11
# 3. isNaN():判断是否为数字
- 是 is Not a Number 的缩写
// 是数字则返回 false
isNaN(10); // false
// 不是数字则返回 true
isNaN("hello"); // true
1
2
3
4
5
2
3
4
5
# 4. Array.isArray():判断是否为数组
var arr = [];
var obj = {};
// Array.isArray(参数),H5新增的方法
console.log(Array.isArray(arr)); // true
console.log(Array.isArray(obj)); // false
1
2
3
4
5
2
3
4
5
# 5. .constructor:判断数据类型
- null 和 undefined 不能判断,因为他们不是由对象构建
- 指向的是最初创建者,而且容易伪造,不适合做类型判断
var arr = []
var obj = {}
var num = 10
var bool = true
var data = new Date()
console.log(arr.constructor === Array) // true
console.log(arr.constructor === Object) // false 这是数组,不是对象
console.log(obj.constructor === Object) // true
console.log(num.constructor === Number) // true
console.log(bool.constructor === Boolean) // true
console.log(data.constructor === Date) // true
console.log("A".constructor === String) // true
1
2
3
4
5
6
7
8
9
10
11
12
2
3
4
5
6
7
8
9
10
11
12
# 6. instanceof:复杂数据类型检测
- 判断某个对象是否属于某种类型
- instanceof是通过原型链来检查类型的,所以适用于任何 object 的类型检查
var arr = [];
var obj = {};
console.log(arr instanceof Array); // true 表示是数组
console.log(obj instanceof Object); // true 表示是对象
// 在 JavaScript 中,数组也属于对象(故在判断数组时,会把数组当做Object类型)
console.log(arr instanceof Object); // true
// 不能检测基本数据类型,判断 null、undefined 会报错
console.log(10 instanceof Number); // false
console.log("A" instanceof String); // false
1
2
3
4
5
6
7
8
9
10
2
3
4
5
6
7
8
9
10
# 数据类型转换
# 1. 数字转化为字符串
var num = 10;
num.toString();
1
2
2
var num = 10;
String(num); // 强制转换
1
2
2
var num = 10;
num + ""; // 隐式转换
1
2
2
# 2. 字符串转化为数字
parseInt("3.14"); // 3 取整(会去掉小数点后面的数字)
parseInt("120px"); // 120 会去掉px单位(会去掉非数字的字符)
1
2
2
Number("3.14"); // 3.14
Number("3"); // 3
1
2
2
// 利用运算符 - * / 转化为数值型(隐式转换)
console.log("12" - 0); // 12
console.log("12" * 1); // 12
console.log("12" / 1); // 12
1
2
3
4
2
3
4
# 3. Boolean():转换为布尔值类型
// 代表空、否定的值会被转换为 false
console.log(Boolean("")); // false
console.log(Boolean(0)); // false
console.log(Boolean(NaN)); // false
console.log(Boolean(null)); // false
console.log(Boolean(undefined)); // false
//其余值都会被转换为 true
console.log(Boolean("hello")); // true
console.log(Boolean(10)); // true
1
2
3
4
5
6
7
8
9
10
2
3
4
5
6
7
8
9
10
# 4. 转化为数组
// 将 一组值 转换为 数组
new Array(3, 11, 8) // [3, 11, 8]
Array.of(3, 11, 8) // [3, 11, 8]
1
2
3
2
3
// 将 字符串 转化为 数组
"abc".split("") // ["a", "b", "c"]
"a,b,c".split(","); // ["a", "b", "c"]
Array.from("abc") // ["a", "b", "c"]
1
2
3
4
5
2
3
4
5
// 将 数字 转化为 数组:先将数字转化为字符串,再转化为数组
String(123).split("") // ["1", "2", "3"]
1
2
2
// 将 对象 转化为 数组
var obj = { name: "张三", age: 18, sex: "男" }
// Object.keys():将对象中的属性名转化为字符串数组
Object.keys(obj) // ["name", "age", "sex"]
// Object.values():将对象中的属性值转化为数组
Object.values(obj) // ["张三", 18, "男"]
1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
# 数组的增、删、改、查
# 1. 创建数组的几种方式
// 1. 使用字面量创建数组
var arr = [1, 2, 3];
// 2. 使用 new Array() 构造函数创建数组
var arr1 = new Array(); // 创建了一个空数组
var arr2 = new Array(2); // 表示数组长度为2(有2个空元素)
var arr3 = new Array(1, 2, 3); // [1, 2, 3]
// 3. 使用 Array.of() 创建数组
var arr1 = Array.of(); // 创建了一个空数组
var arr2 = Array.of(1, 2, 3); // [1, 2, 3]
1
2
3
4
5
6
7
8
9
10
11
2
3
4
5
6
7
8
9
10
11
# 2. 数组名[索引号]:增/删/改数组元素
var arr = ["red","green","blue"];
// 增加数组元素
arr[3] = "yellow"; // ["red", "green", "blue", "yellow"]
// 修改数组元素
arr[1] = "yellow"; // ["red","yellow","blue"];
// 删除数组元素
delete arr[0]; // ["空","green","blue"],数组长度不变
1
2
3
4
5
6
7
2
3
4
5
6
7
# 3. push()、unshift():在数组的尾部、头部添加一个或多个元素
var arr = [1, 2, 3];
// 数组名.push():在尾部添加元素
arr.push(4, "jack"); // [1, 2, 3, 4, "jack"]
// 数组名.unshift():在头部添加元素
arr.unshift(0, "red"); // [0, "red", 1, 2, 3]
1
2
3
4
5
6
2
3
4
5
6
# 4. concat():连接两个或多个数组
var arr = [1, 2, 3];
var arr2 = [6, 7];
// 把 concat() 中的参数连接到数组 arr 中,返回一个新的数组
var newArr = arr.concat(4, 5, arr2)
console.log(newArr); // [1, 2, 3, 4, 5, 6, 7]
1
2
3
4
5
2
3
4
5
# 5. 删除数组元素
var arr = ["red", "pink", "blue"];
// 数组名.pop():删除最后一个元素
arr.pop(); // ["red", "pink"]
// 数组名.shift():删除第一个元素
arr.shift(); // ["pink", "blue"]
// 数组名.splice(第几个开始,删除几个元素):删除多个元素
arr.splice(1,2); // ["red"]
1
2
3
4
5
6
7
8
9
10
2
3
4
5
6
7
8
9
10
# 6. indexOf()、lastIndexOf():查找数组元素的位置
var arr = ["北京", "上海", "广州", "深圳", "上海", "北京"];
// 变量名.indexOf(数组元素):多个相同元素只返回头一个,元素不存在则返回-1
arr.indexOf("上海") // 1 返回索引号
arr.indexOf("成都") // -1 元素不存在返回-1
// 变量名.lastIndexOf(数组元素):多个相同元素只返回最后一个,元素不存在则返回-1
arr.lastIndexOf("北京") // 5 返回索引号
arr.lastIndexOf("成都") // -1 元素不存在返回-1
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
# 7. 数组排序(翻转数组、从大到小/从小到大排列)
var arr = [13, 4, 77, 1, 7];
// 数组名.reverse():将数组元素倒过来(翻转数组)
arr.reverse(); // [7, 1, 77, 4, 13]
// 数组名.sort():将数组元素从小到大/从大到小排列
arr.sort(function (a, b) {
return a - b; // 从小到大
// return b - a; // 从大到小
});
console.log(arr); // [1, 4, 7, 13, 77]
1
2
3
4
5
6
7
8
9
10
11
2
3
4
5
6
7
8
9
10
11
# 8. 随机数组(将数组中的元素随机排列)
let arr = ["张三", "李四", "王五", "赵六"]
arr.sort(() => Math.random()-0.5) // ["李四", "赵六", "王五", "张三"]
// 完整写法
arr.sort(function() {
return Math.random() - 0.5
})
1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
# 对象的增、删、改、查
# 1. 创建对象的几种方式
// 1. 使用字面量创建对象
var obj = { name: "张三", age: 20, sayHi: function() {} }
// 2. 使用 new Object() 创建对象
var obj = new Object() // 创建一个空对象
// 3. 利用 构造函数 创建对象
function Star(name, age) {
this.name = name;
this.age = age;
}
// 使用构造函数创建对象的作用:把对象中相同的属性和方法,封装到函数里面,方便复用
var obj1 = new Star("张三", 20)
console.log(obj1) // { name: "张三", age: 20 }
var obj2 = new Star("李四", 18)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# 2. 查找/添加/修改对象中的属性和方法
var obj = {
name: "张三",
age: 20,
sayHi: function() {
console.log("你好,我是张三")
}
}
// 查
obj.name // 张三
obj["name"] // 张三
obj.sayHi() // 调用对象中的方法
// 添加 和 修改 对象的属性和方法
obj.sex = "男", // 如果对象中没有这个属性/方法,则会添加
obj.age = 20, // 如果对象中存在这个属性/方法,则会修改
obj.sayHi = function() {}
// 删除对象中的某个属性
delete obj.name // 删除对象中的 name 属性
// 清空对象中的每个 value 值
Object.keys(obj).map(key => obj[key] = "") // {name: "", age: "", sayHi: ""}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# 遍历数组的几种方式
# 1. for循环:遍历数组
- 可以搭配 continue 和 break 使用(跳出/结束循环)
const arr = ["清华", "北大", "复旦", "浙大", "中科大"]
// 循环遍历数组中的每一个元素
for(let i = 0; i < arr.length; i++) {
console.log(arr[i]);
}
1
2
3
4
5
6
2
3
4
5
6
# 2. forEach():遍历数组
- 语法格式:数组名.forEach(function(value, index, arr))
- value:每个数组元素
- index:每个数组元素的索引号
- arr:数组本身
- 注意:forEach 循环一旦开始,无法在中间被停止
var arr = ["清华", "北大", "复旦"];
arr.forEach(function(value, index, array) {
console.log("每个数组元素:" + value);
// console.log("每个数组元素的索引号:" + index);
// console.log("数组本身:" + array);
})
1
2
3
4
5
6
7
2
3
4
5
6
7
# 3. filter():筛选数组中的元素
- 语法格式:数组名.filter(function(value, index, arr))
- 注意:它返回的是一个新的数组(把所有符合条件的元素,存放到新数组)
var arr = [12, 66, 4, 88];
// filter 筛选数组:返回的是一个新的数组
var newArr = arr.filter(function(value, index) {
return value >= 20; // 把所有大于等于20的元素筛选出来,存放到新数组中
})
console.log(newArr); // [66, 88]
// ES6中的写法
var newArr = arr.filter((value, index) => value >= 20)
console.log(newArr); // [66, 88]
1
2
3
4
5
6
7
8
9
10
11
2
3
4
5
6
7
8
9
10
11
# 4. some():查找数组中是否有满足条件的元素
- 语法格式:数组名.some(function(value, index, arr))
- 返回值是布尔值,查找到这个元素就返回 true,否则返回 false
- 当找到第一个满足条件的元素,返回 true 并终止循环,不再继续查找
- 使用场景:如果查询数组中唯一的元素,用 some 更合适,因为它找到了这个元素,就结束循环不再继续查找,效率更高
var arr = [12, 66, 4, 88];
// some 查找数组中是否有满足条件的元素
var flag = arr.some(function(value, index) {
console.log("这是第" + index +"次循环"); // 当找到第一个满足条件的元素,则终止循环
return value >= 20; // 元素是否满足条件,满足则返回true,并终止循环,不再继续查找
})
console.log(flag); // true
// ES6写法
const arr1 = ["red", "green", "blue"];
var flag1 = arr1.some((value) => value === "yellow")
console.log(flag1); // false
1
2
3
4
5
6
7
8
9
10
11
12
13
2
3
4
5
6
7
8
9
10
11
12
13
# 5. every():检测数组元素是否都满足条件
- 语法格式:数组名.every(function(value, index, arr))
- 注意:遇到不满足条件的元素,则返回 false 并终止循环不再继续查找
var arr = [12, 66, 4, 88];
// every 用于检测数组元素是否都满足条件
var flag = arr.every(function(value, index) {
console.log("这是第" + index +"次循环"); // 当找到第一个不满足条件的元素,则终止循环
return value >= 10; // 元素是否满足条件,不满足则返回false,并终止循环,不再继续查找
})
console.log(flag); // false
1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
# 遍历对象的几种方式
# 1. for...in 循环:遍历对象的键/值
- 可以搭配 continue 和 break 使用(跳出/结束循环)
const obj = { name: "jack", age: 18, sex:"男" }
// 循环遍历对象中的每一个键/值
for (const key in obj) {
console.log("属性名为:",key); // name age sex
console.log("属性值为:",obj[key]); // jack 18 男
}
// 可以搭配 continue 和 break 使用(跳出/结束循环)
for (const key in obj) {
if(obj[key] === 18) {
break // 结束整个循环
}
console.log(obj[key]); // jack
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# 2. Object.keys() 和 Object.values() 配合 forEach 实现遍历对象
- 语法格式:Object.keys(对象名) 和 Object.values(对象名)
- Object.keys():把对象的属性名转换为数组
- Object.values():把对象的值转换为数组
const obj = { name: "jack", age: 18, sex:"男" }
// Object.keys() 把对象的属性名转换为数组
key = Object.keys(obj)
console.log(key); // ["name", "age", "sex"]
// Object.values() 把对象的值转换为数组
value = Object.values(obj)
console.log(value); // ["jack", 18, "男"]
// 可以配合 forEach() 或 其他方法 遍历数组中的元素
Object.keys(obj).forEach(function(value) {
console.log(value); // name age sex
})
Object.values(obj).forEach(function(value) {
console.log(value); // jack 18 男
})
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# 判断数组中是否存在某个元素
var arr = ["a", "b", "c"]
// 1. indexOf():返回该元素在数组中的下标位置,如果该元素不存在则返回 -1
arr.indexOf("b"); // 1
arr.indexOf("d"); // -1
// 2. includes():如果存在则返回 true,否则 false
arr.includes("b"); // true
arr.includes("d"); // false
// 3. 传统 for() 循环
for (let i = 0; i < arr.length; i++) {
if (arr[i] === "b") {
console.log("包含该元素");
}
}
// 4. for...of
for (const item of arr) {
if(item === "b") {
console.log("包含该元素");
}
}
// 5. forEach()
arr.forEach(function(item) {
if(item === "b") {
console.log("包含该元素");
}
})
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# 判断对象中是否存在某个属性
var obj = { a: 1, c: undefined }
// 1. !== :可以判断继承来的属性,属性值为 undefined 时,无法判断
obj.a !== undefined; // true
obj.c !== undefined; // false
obj.toString !== undefined; // true
// 2. Object.keys(对象).includes(属性名):无法判断继承来的属性
Object.keys(obj).includes("a"); // true
Object.keys(obj).includes("c"); // true
Object.keys(obj).includes("toString"); // false
// 3. hasOwnProperty():无法判断继承来的属性
// 用来判断某个对象是否含有指定的属性,返回布尔值,当检测属性为自有属性(非继承)的时候返回 true
// 适用于只判断自身属性的场景
obj.hasOwnProperty("a"); // true
obj.hasOwnProperty("c"); // true
obj.hasOwnProperty("toString"); // false
// 4. in 运算符:可以判断继承来的属性,属性值为 undefined 时,也可以判断
// 如果指定的属性在指定的对象或其原型链中,则 in 运算符返回 true
console.log("a" in obj); // true
console.log("c" in obj); // true
console.log("toString" in obj); // true
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# 数组去重
# 1. new set():实现数组去重、并集、交集、差集(强烈推荐)
// 数组去重
var arr = [1,2,3,3,1,4];
[...new Set(arr)]; // [1, 2, 3, 4]
Array.from(new Set(arr)); // [1, 2, 3, 4]
// 字符串去重
[...new Set('ababbc')].join(''); // "abc"
new Set('ice doughnut'); // Set(11) {"i", "c", "e", " ", "d", …}
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
var a = new Set([1, 2, 3]);
var b = new Set([4, 3, 2]);
// 并集
var union = new Set([...a, ...b]); // {1, 2, 3, 4}
// 交集
var intersect = new Set([...a].filter(x => b.has(x))); // {2, 3}
// 差集
var difference = new Set([...a].filter(x => !b.has(x))); // {1}
1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
# 2. indexOf() 配合循环来实现去重
let arr = ['one','two','three','one','three','two','four'];
let indexArr = [];
arr.forEach(item => {
if(indexArr.indexOf(item)===-1){
indexArr.push(item);
};
});
console.log(indexArr); // ['one','two','three','four'];
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
# 3. 利用 filter() 实现去重
let arr = ['one','two','three','one','three','two','four'];
let el = arr.filter((item,index)=>arr.indexOf(item)===index);
console.log(el); // ['one','two','three','four'];
1
2
3
4
2
3
4
# 4. 利用 对象特性 实现去重
/*
1.声明一个对象 obj,利用对象特性
2.循环每一项复印,使用 keys(values) 方法取出 key 值
*/
var arr = ['one','two','three','one','three','two','four'];
// 对象方法 和 for循环
var obj = {};
for(var i=0;i<arr.length;i++){
obj[arr[i]] = arr[i];
};
var el = Object.keys(obj);
console.log(el) // ['one','two','three','four'];
// 对象方法 和 arr.forEach
var obj = {};
arr.forEach(function(ele,index,arr){
obj[arr[index]] = arr[index];
});
var el = Object.keys(obj);
console.log(el) // ['one','two','three','four'];
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# 字符串常用方法
# 1. length:获取字符串/数组的长度
var str = "hello"
str.length // 5,表示长度为5
1
2
2
# 2. indexOf():根据字符查找位置,返回的是索引
var str = "改革春风吹满地,春天来了";
console.log(str.indexOf("春")); // 2 根据字符查找位置(返回的是索引号)
console.log(str.indexOf("春",3)); // 8 (参数3表示,从索引号3开始查找春)
console.log(str.lastIndexOf("春")); // 8 返回的是最后一个"春"的索引号(从后往前查找)
1
2
3
4
2
3
4
# 3. charAt():根据索引号查找字符
var str = "改革春风吹满地,春天来了";
console.log(str.charAt(2)); // 春
console.log(str1.charCodeAt(0)); // 97(返回相应索引号的ASCII值,判断用户按了哪个键)
console.log(str[2]); // 春 (根据索引号查找字符)
1
2
3
4
2
3
4
# 4. concat():拼接字符串
var str1 = "hello"
var str2 = "world"
str1.concat(str2) // helloworld
1
2
3
2
3
# 5. substr():截取字符串
var str = "helloword";
console.log(str.substr(5)); // word 表示从索引号5开始截取
console.log(str.substr(0,5)); // hello 表示从索引号0开始截取,取5个字符
1
2
3
2
3
# 6. replace():替换字符串中的字符
var str = "我不喜欢你";
console.log(str.replace("不","很")); // 我很喜欢你
console.log(str.replace("不","")); // 我喜欢你
1
2
3
2
3
# 7. trim():删除字符串首尾空白字符
var str = " hello ";
str.trim(); // hello
1
2
2
# 8. split():将字符串转为数组
var str1 = "hello";
str1.split(); // ["hello"]
var str2 = "I Love You"
str1.split(" "); // ["I", "Love", "You"]
var str3 = "1,2,3,4,5"
str3.split(","); // ["1", "2", "3", "4", "5"]
1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
# 8. toUpperCase():字符串大小写转化
var str = "hello";
console.log(str.toUpperCase()); // HELLO
console.log(str.toLowerCase()); // 转化为小写
console.log(str.charAt(0).toUpperCase() + str.slice(1)); // 首字母大写
1
2
3
4
2
3
4