本次笔记记录一下个人关于数组没掌握好的一些知识点
arra.of用来创建单个数组
//当我们想创建数组中只有一个元素,且元素值为1的时候
let arr1 = new Array(1)
console.log(arr1)//很显然,打印出的却是长度为1的空数组
//正确方法来了
let arr2 = Array.of(1)
console.log(arr2)
数组转化成字符串
//方法一
let arr1 = ['0','1','2','3','4']
let str1 = arr1.toString()
console.log(str1)
//方法二
let arr2 = ['0','1','2','3','4']
let str2 = new String(arr2)
console.log(str2)
//方法三
let arr3 = ['0','1','2','3','4']
let str3 = arr3.join('-')
console.log(str3)
字符串转数组
let str = '123456'
let arr = str.split("")
console.log(arr)
伪数组就是具有length属性
常见的伪数组:string(对,字符串也是) nodelist(获取的一系列dom元素)
//就只举例字符串吧
let str = '123456'
let arr = Array.from(str,(item)=>{
return item + 1
})
//最后结果是返回["11", "21", "31", "41", "51", "61"]
//因为这里的item是字符内
console.log(arr)
就是去掉[ ],或者理解是分散开一个集中的变量
let arr1 = ['1','2']
let arr2 = ['3','4']
arr1 = [...arr1,...arr2]
console.log(arr1)
let [num1,num2] = [1,2]
console.log(num1,num2)
增加
let array = [1,2,3,4,5,6,7]
//添加到后面
array.push(8)
console.log(array)
//添加到前面
array.unshift(0)
console.log(array)
删除
let array = [1,2,3,4,5,6,7]
//从后面删除
array.pop()
console.log(array)
//从前面删除
array.shift()
console.log(array)
清空
let array = [1,2,3,4,5,6,7]
array.length = 0
console.log(array)
slice操作
let array = [1,2,3,4,5,6,7]
console.log(array.slice(1,2))//从第一个开始,到第二个结束,(]结构
splice操作
//删除
let array = [1,2,3,4,5,6,7]
console.log(array.splice(1,2))//从第一个开始,截取2个,(]
console.log(array)
//替换功能
let array = [1,2,3,4,5,6,7]
console.log(array.splice(1,2,7,8))//从第一个开始,截取2个,(],然后替换为 7 8
console.log(array)
//增加
let array = [1,2,3,4,5,6,7]
console.log(array.splice(0,0,8))//从第0个开始,截取0个,(],然后添加8
console.log(array)
数组的查找
let array = [1,2,3,4,5,6,5,7]
console.log(array.indexOf(5))//查找5这个元素的索引
console.log(array.includes(5))//查找是否有5这个元素
//但是include无法查找引用类型,find可以
console.log(array.find(item=>{
//返回的是值
return item == 2
}))
console.log(array.findIndex(item=>{
//返回的是索引
return item == 2
}))
数组排序
let array = [1,2,3,4,5,6,5,7]
array = array.sort(function(a,b){
return b-a
//降序
})
console.log(array)
array = array.sort(function(a,b){
return a-b
})
console.log(array)