Fork me on GitHub

前端基础-基础数据类型及原生方法

JS 数据类型

基础数据类型

  • Number
  • String
  • Boolean
  • Null
  • Undefined
  • Symbol

引用数据类型

  • Object
  • Array
  • Function

数据结构

  • Map
  • Set

String 原生方法

Number 原生方法

Object 原生方法

Object 遍历

Array 原生方法

Array 遍历

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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
let arr = [1,2,3,4,5]

// 1.for 循环
for(let i = 0; i < arr.length; i++) {
console.log(arr[i])
}

// 2.for of
for(let it of arr) {
console.log(it)
}

// 3.forEach
arr.forEach((it, index, _arr) =>{
console.log(it, index, _arr)
})

// 4.map(参数为回调函数)函数,遍历数组每个元素,并回调操作,需要返回值,返回值组成新数组,原数组不变;
let arrMap = arr.map((it, i)=>{
console.log(it, i)
return it+1
})
console.log(arrMap)

// 5.filter(参数为回调函数)函数:过滤通过条件的元素组成一个新数组,原数组不变;
let arrFilter = arr.filter((it, i)=>{
console.log(it, i)
return it > 2
})
console.log(arrFilter)

// 6.some(参数为回调函数)函数,遍历数组中是否有符合条件的函数,返回布尔值;
const arrSome = arr.some((it,i) => {
console.log(it, i)
return it === 2
})
console.log(arrSome)

// 7.every(参数为回调函数)函数,遍历数组是否每个元素都符合条件,返回布尔值;
const arrEvery = arr.every((it,i) => {
console.log(it, i)
return it > 0
})
console.log(arrEvery)

// 8.find()函数,数组中的每个元素都执行这个回调函数;返回第一个满足条件的元素 之后的元素就不在调用;没有符合的返回undefined;并没有改变数组的原始值。
const arrFind = arr.find((it,i) => {
console.log(it, i)
return it > 2
})
console.log(arrFind)

// 9.reduce(),合并二维数组
var sum = arr.reduce((res, it)=>{
console.log(it)
res += it
return res
}, 0);
console.log(sum)

如何判断数据类型?

  • typeof xxx:能判断出number,string,undefined,boolean,object,function(null是object)
  • Object.prototype.toString.call(xxx):能判断出大部分类型
  • Array.isArray(xxx):判断是否为数组

typeof xxx 正常够用

能判断出number,string,undefined,boolean,object,function, BigInt, Synmol,
null判断为object: 因为底层存储为二进制 null 为000开头,与object类型一致,导致判断出错
array 判断为 object: 原因同上

Object.prototype.toString.call(xxx) 强烈建议

Array.isArray

Array.isArray 可以判断数组

坚持原创技术分享,您的支持将鼓励我继续创作!