前几天面试字节,死在数组身上。总结还是刷题太少,对数组的操作不是很熟悉。最近又开始了枯燥的刷题,与此同时又对数组进行了系统性的学习。总结为这篇学习笔记。有想一起刷题的小伙伴可以私聊我,一块进行枯燥的刷题时间。唯有熟能生巧
// 字面量方式:
// 这个方法也是我们最常用的,在初始化数组的时候 相当方便
var a = [3, 11, 8]; // [3,11,8];
// 构造器:
// 实际上 new Array === Array,加不加new 一点影响都没有。
var a = Array(); // []
var a = Array(3); // [,,]
var a = Array(3,11,8); // [ 3,11,8 ]
let arr = new Array(6)
console.log(arr.length) //6
let arr = Array.of(6)
console.log(arr) //6
console.log(Array.isArray("das")) //false
console.log(Array.isArray(12)) //false
console.log(Array.isArray([])) //true
let t = [1,2,5,6,7].toString()
console.log(typeof t) //'string'
let t = String([1,2,3,5])
console.log(typeof t) //'string'
let t = [1,2,3,5].join("")
console.log(typeof t) //'string'
let str = "Jack"
console.log(str.split("")) //["J","a","c","k"]
let str = "Jack"
//使用 Array.from 必须保证有length属性
console.log(Array.from(str)) //["J","a","c","k"]
如何连接两个字符串:
let arr1 = ["sda","qwqw"]
let arr2 = ["asdas"]
for(const value of arr2){
arr1.push(value)
}
arr = [...arr1,...arr2]
Sum function:
function sum(...args){
return args.reduce((s,v)=>{
return (s+=v)
},0)
}
console.log(sum(1,2,3,5,4,6,7,8)) //34
console.log(sum(1,2,3,4)) //10
let arr= [2,3]
let [a,b] = arr;
console.log(a,b) // 2 3
const [...arr] = "Jack"
//["J","a","c","k"]
let [,b] = [22,68]
console.log(b) //68
let [a,...b] = [56,98,2,5,555,232]
console.log(b) //98,2,5,555,232
let [a,b=2] = [1]
console.log(a) //1
let arr1 = ["qwewq","4ew"]
let arr2 = ["3423","ewtwe"]
console.log([...arr1,...arr2])
console.log(arr1.push("eqw",...arr2))
function test(begin,end){
let arr = []
for(let i=begin;i<=end;i++){
arr.push(i)
}
return arr
}
let arr = [1,2,3,5]
arr.pop() //1 2 3
arr.unshift(0,6) //0 6 1 2 3
arr.shift() //0
console.log(Array(5).fill(1)) //1 1 1 1 1
console.log([1,2,3,4,5,6].fill("jack",1,3)) //[1, "jack", "jack", 4, 5, 6]
2020/6/18
今天在Codewars上刷题时,使用splice
方法在for循环上遇到了坑。
题目要求很简单:删除前后一样的元素。
第一次进行尝试解决:
function uniq (s) {
let str = s[0]
for (let i = 1; i < s.length; i++) {
s[i] == str ? s.splice(i, 1) : str = s[i]
}
return s
}
uniq(['a', 'a', 'b', 'b', 'c', 'a', 'b', 'c']) //['a', 'b', 'b', 'c', 'a', 'b', 'c']
注意:这块只删除了一个元素,而最终结果是[‘a’, ‘b’, ‘c’, ‘a’, ‘b’, ‘c’]
虽然学了splice,但是不使用的话,还是会遗忘其细节。
splice 是直接操作并修改数组的,所以当找到a时在循环中的 i 下标是1,而当删除a后,数组下标 i 位置中保存的字符串变为了第二个b,然后到了下一个循环 i 下标为2时,数组下标 i 位置中保存的字符串c,所以跳过了字符串b的对比,于是最终返回结果中多余一个b
更改代码
function uniq (s) {
let str = s[0]
for (let i = 1; i < s.length; i++) {
if (s[i] == str) {
s.splice(i, 1)
i = i - 1
}
else {
str = s[i]
}
}
return s
}
const uniq = a => a.filter(function (x, i) { return i == 0 || !(a[i - 1] == x); })
let arr = [1,2,3,5,6,9]
//截取部分 有始有终
let newArr = arr.slice(1,3)
console.log(newArr)// 2 3
console.log(arr)// 1 2 3 5 6 9
//截取全部
console.log(arr.slice()) // 1 2 3 5 6 9
// 从index开始之后所有
console.log(arr.slice(1)) // 2 3 5 6 9
let arr = [1,2,3]
// 截取之后 直接拿走 改变原数组
let newArr = arr.splice(0,2)
console.log(newArr) //1 2
console.log(arr) //3
let arr1 = [1,2,3]
// 替换 并 移除
let arr2 = arr1.splice(0,2,"jack","yjk")
console.log(arr2) //["jack", "yjk", 3]
let arr3 = [1,2,5,9,7]
arr3.splice(1,1,"yjk")
console.log(arr3) // [1, "yjk", 5, 9, 7]
//当 第二个参数为0 进行增加
let arr4 = [1,2,5,9,7]
arr4.splice(1,0,"yjk")
console.log(arr4) // [1, "yjk", 2, 5, 9, 7]
function moveEl(array,from,to){
//判断位置 是否合法
if(from <0 || to >= array.length){
console.error("参数错误")
return
}
// 定义新数组 从而不改变原来的数组
const newArray = [...array]
let item = newArray.splice(from,1)
newArray.splice(to,0,...item)
return newArray
}
let array = [1,2,3,4,5]
// 把 第一个元素 移动到 第三个位置
console.log(moveEl(array,1,3)) //[1, 3, 4, 2, 5]
let arr = [1,2,3,3,6]
arr = []
arr.length = 0
arr.splice(0,arr.length)
while(arr.pop()){}
// 直接赋值为空 arr2 指向 [1,2,3] arr1 指向空
let arr1 = [1,2,3]
let arr2 = arr1
arr1= []
console.log(arr2) //[1, 2, 3]
console.log(arr1) // []
//设置数组长度为0 两个数组都指向 空
let arr1 = [1,2,3]
let arr2 = arr1
arr1.length = 0
console.log(arr2) //[]
console.log(arr1) // []
let str = "qw,er,rt"
let arr = str.split(",") //[qw,er,rt]
arr,join("-") //qw-er-rt
let arr1 = [1,2]
let arr2 = [1,2]
let arr3 = [1,2]
arr1 = arr1.concat(arr2,arr3)
arr1 = [...arr1,...arr2,...arr3]
let arr = [1,2,3,4]
console.log(arr.copyWithin(2,0,2)) //[1,2,1,2]
let arr = [1,2,3,4,5,6]
console.log(arr.copyWithin(3,1,3)) //[1,2,3,2,3,6]
let arr = [1,2,3,4,2]
//indexOf 从左侧开始查找
//lastIndexOf 从右侧开始查找
// 返回 2的索引位置
console.log(arr.indexOf(2)) //1
console.log(arr.indexOf(5)) //-1 查找不到返回-1
console.log(arr.lastIndexOf(2)) //4
//从第二个位置开始查找 2 (el,begin)
console.log(arr.indexOf(2,2)) //4
// 右侧第二个开始进行查找
console.log(arr.lastIndexOf(2,-2)) //4
console.log(arr.includes(2)) //true
function includes(array,find){
for(const value of array){
if(value === find) return true
return false
}
}
let arr = [1,2,3,4,5]
let res = arr.find(function(item){
//console.log(item)
return item == 2
})
console.log(res) //2
let lessons = [{name:"js"},{name:"css"},{name:"html"}]
let status = lessons.find(function(item){
//console.log(item)
return item.name == "css"
})
console.log(status) //{name:'css'}
let statusIndex = lessons.findIndex(function(item){
//console.log(item)
return item.name == "css"
})
console.log(statusIndex) // 1
function find(array,callback){
for(const value of array){
if(callback(value)) return value
}
return undefined
}
let arr= [1,2,3,4,5]
console.log(find(arr,function(item){
return item == 22
}))
// undefined
Array.prototype.findValue = function(callback){
for(const value of this){
if(callback(value)) return value
}
return undefined
}
let arr= [1,2,3,4,5]
const res = arr.findValue(function(item){
return item == 2
})
console.log(res) // 2
let arr = [1,2]
arr = arr.sort(function(a,b){
// return a-b //从小到大
// return a-b //从大到小
return a-b
})
console.log(arr) // 1 2
let arr = [4,3,5,1,2,9,78]
function sort (array,callback){
for(const n in array){
for(const m in array){
if(callback(array[n],array[m]) < 0){
const temp = array[n]
array[n] = array[m]
array[m] = temp
}
}
}
return array
}
arr = sort(arr,(a,b) => a-b)
console.log(arr) //[1, 2, 3, 4, 5, 9, 78]
let list = [
{id:1,name:"asdas"},
{id:1,name:"sf"},
{id:1,name:"wer"}
]
for(let i=0;i<list.length;i++){
list[i].name = `test ${list[i].name}`
}
console.table(list)
for(const value of list){
value.name = `test ${value.name}`
}
console.table(list)
注意:当数组中为值类型的时候,进行数据更改,不会更改原有数组内容
let arr = [1,2,3]
for(let value of arr){
value += 10
}
console.log(arr) // [1,2,3]
for(const key in list){
list[key].name = `test ${list[key].name}`
}
list.forEach(function(item,index,list){
console.log(item)
})
list.forEach(function(item,index,list){
console.log(index)
})
list.forEach(function(item,index,list){
console.log(list)
})
list.forEach(function(item,index,list){
item.name = item.name.substr(0,5)
})
console.table(list)
forEach 可以直接操作 DOM 元素
let arr = [1,2,3]
let keys = arr.keys()
let values = arr.values()
console.log(keys) // Array Iterator{}
console.log(keys.next()) //{value:1,done:false} false代表后面还有值
while(({value,done} = values.next()) && done === false){
console.log(value)
} // 1 2 3
取值:
let arr = [1,2,3]
for(const value of arr.values()){
console.log(value)
} // 1 2 3
取索引值:
let arr = [1,2,3]
for(const key of arr.keys()){
console.log(key)
} // 0 1 2
let str = ["jack","yjk"]
let entries = str.entries()
let {done,value} = entries.next()
console.log(done,value) // false [0, "jack"]
let str = ["jack","yjk"]
for(const [key,value] of arr.entries()){
console.log(value)
}
// jack yjk
const list = [
{name:"asd",num:90},
{name:"asd",num:70},
{name:"asd",num:55}
]
let res = list.every(function (item){
return item.num >= 60
})
if(res){
console.log("True")
}else{
console.log("False")
}
//False
let res = list.some(function (item){
return item.num >= 60
})
if(res){
console.log("True")
}else{
console.log("False")
}
//True
let arr = [1,2,3,4]
let newArr = arr.filter(function(value,index,arr){
return true
})
console.table(newArr)
let list = [
{id:1,name:"asdas"},
{id:2,name:"sf"},
{id:1,name:"wer"}
]
let res = list.filter(function(list){
return list.id === 1
})
console.log(res)
let arr = [1,2,3,4,5,6,7,8,9]
function filter(array,except){
let newArray = []
for(const value of array){
if(except.includes(value) === false){
newArray.push(value)
}
}
return newArray
}
console.log(filter(arr,[4,5,6])) //[1, 2, 3, 7, 8, 9]
// 判断偶数
let arr = [1,2,3,4,5,6,7,8,9]
function filter(array){
let newArray = []
for(const value of array){
if(value%2 === 0){
newArray.push(value)
}
}
return newArray
}
console.log(filter(arr))
let arr = [1,2,3,4,5,6,7,8,9]
function filter(array,callback){
let newArray = []
for(const value of array){
if(callback(value) === true){
newArray.push(value)
}
}
return newArray
}
console.log(filter(arr,function(value){
return value%2===0
}))
let arr = [1,2,3,4,5,6]
let arr1 = arr.map(function(value,index,arr){
value += 2
return value
})
console.log(arr1) // [3, 4, 5, 6, 7, 8]
console.log(arr) // [1,2,3,4,5,6]
let list = [
{id:1,name:"asdas"},
{id:2,name:"sf"},
{id:1,name:"wer"}
]
list.map(function(value){
value.other = "test"
})
console.table(list)
引用类型 不想改变原数组:
第一种:
let list = [
{id:1,name:"asdas"},
{id:2,name:"sf"},
{id:1,name:"wer"}
]
let newArr = list.map(function(value){
return Object.assign({other:"test"},value)
})
console.table(list)
console.table(newArr)
第二种:
let list = [
{id:1,name:"asdas"},
{id:2,name:"sf"},
{id:1,name:"wer"}
]
let newArr = list.map(function(value){
return {
id:value.id,
name:value.name,
other:"test"
}
})
console.table(list)
console.table(newArr)
let arr = [1,2,3,4,5,6]
arr.reduce(function(pre,value,index,array){
console.log(pre,value)
return 12
})
arr.reduce(function(pre,value,index,array){
console.log(pre,value)
return 12
},0)
在第二个中 0为当前reduce中的 pre 的值
例子1:查询出现的次数
let arr = [1,2,5,6,2,3,4,2,6,1]
function arrayCount(array,item){
return array.reduce(function(total,cur){
total += item === cur ? 1 : 0
return total
},0)
}
console.log(arrayCount(arr,1)) // 2
例子2:查询最大值
let arr = [56,89,51,78,63,21,59,99]
function arrayMax(array,item){
return array.reduce(function(pre,cur){
return pre > cur ? pre : cur
})
}
console.log(arrayMax(arr)) // 99
数组去重:
let arr = [1,2,3,5,6,4,1,2,6,5,2,1]
let newArr = arr.reduce(function(arr,cur){
if(arr.includes(cur) === false){
arr.push(cur)
}
return arr
},[])
console.log(newArr) // [1, 2, 3, 5, 6, 4]