探究数组方法的使用技巧
探究数组方法的使用技巧
转字符方法
Array.prototype.toString
Array.prototype.toString 数组无论被嵌套多少层都会被转成 String
1 | |
Array.prototype.join
Array.prototype.join 将数组各成员按照某字符串进行连接并且装换成 String,与String.prototype.split 相对应
1 | |
堆栈方法
Array.prototype.push Array.prototype.pop
Array.prototype.push 数组末尾添加元素 ,返回长度
Array.prototype.pop 数组末尾去除元素 ,返回去除项
1 | |
Array.prototype.unshift Array.prototype.shift
Array.prototype.unshift 数组头部添加元素 ,返回长度
Array.prototype.shift 数组头部去除元素 ,返回去除项
1 | |
堆栈方法均改变原数组
排序方法
Array.prototype.reverse
Array.prototype.reverse 排序和其中元素大小无关,反转数组,改变原数组 , 视觉上反转数组
1 | |
Array.prototype.sort
Array.prototype.sort
当arr.sort()不传入函数时,会将数组数组中的各元素转成 String , 再按照每个 String 的 Unicode 编码大小比较,进行升序排列,改变原数组
1 | |
针对元素为数字字符串和数字的排序
Array.prototype.sort 为 高阶函数 ,给其传入一个 回调函数 ,根据返回值不同可以控制 升序 或者 降序
1 | |
拼接方法
Array.prototype.concat
Array.prototype.concat 主要用于拼接数组,返回新数组,不改变原数组
1 | |
等价于使用 展开运算符 拼接数组
1 | |
删改方法
Array.prototype.slice
Array.prototype.slice(start,end) 从数组start项截取到end项,左闭右开,返回截取元素组成的新数组,不改变原数组
1 | |
Array.prototype.splice
Array.prototype.splice(start,删除的个数,添加的值) 可以删除或添加值,返回删除的值,改变原数组
1 | |
查找方法
Array.prototype.indexOf & Array.prototype.lastIndexOf
Array.prototype.index 正向查询某值在数组中的位置,有即返回索引
Array.prototype.lastIndexOf 反向查询某值在数组中的位置,有即返回索引
1 | |
Array.prototype.includes
Array.prototype.includes 查询是否有值,有即返回 true
1 | |
本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!