Array.from 类阵列转换
NodeList & HTMLCollection 类阵列转换成阵列已写另成一篇文 点我~Array.from 用于阵列转换Array.from 亦可用来转换 Set & MapSet 可以用来去重
const arr = [1, 2, 2, 3] const newArr = Array.from(new Set(arr)) console.log(newArr) // [1, 2, 3]
字串 & 阵列转换
阵列转换成字串 join(),若不传值 会以 , 作为分割用字串转阵列 split()字串转阵列 Array.from() // join() 阵列转换成字串 const strArr = ['A', 'B', 'C'] let defaultStr = strArr.join() let spaceStr = strArr.join('') let str = strArr.join('、') console.log(defaultStr) // A,B,C console.log(spaceStr) // A B C console.log(str) // A、B、C // split() 字串转阵列 const str = '1 2 3 4 5 6' // ["1", "2", "3", "4", "5", "6"] console.log(str.split(' ')) // Array.from() 字串转阵列 cosnt str = 'foo' console.log(Array.from(str)) // ["f", "o", "o"]
字串反转
split() 将字串转成阵列reverse() 反转阵列join() 将阵列合併字串 const str = 'Mom Get The Camera' const result = str.split('').reverse().join('') console.log(result)
产生一个範围的数字阵列
丢个连结 此文写的太好惹 推荐
数字阵列找最大最小值
ES6 rest parameter const numArr = [1, 2, 3, 4, 5] console.log('最大值', Math.max(...numArr)) console.log('最小值', Math.min(...numArr))
实用小技巧
使用length 作清空阵列 & 删除末项,效能较pop佳利用length 判断阵列是否为空利用length 加长阵列会以undefined填补空缺 (不佳别做!) // length let arr = [1, 2, 3] arr.length = 2 console.log(arr) // [1, 2] arr.length = 0 console.log(arr) // [] const emptyArr = [] console.log(emptyArr.length === 0) //true const arrPlus = [1, 2, 3] arrPlus.length = 5 // [1, 2, 3, undefined, undefined] // GoogleChrome 显示 empty !? console.log(arrPlus)
参考资料
MDN
andyyou
Summer。桑莫。夏天
StackOverFlow产数字阵列