Array数组类型的方法 整理
1. slice(start,end)数组复制
- start 参数必须,规定从何处开始选取。如果是负数,那么它规定从数组尾部开始算起的位置
end 参数不必须,规定从何处结束选取 - 返回值 返回一个新数组,不改变原数组
- 举例 console.log([1,2,3,4].slice(1)) //返回[2,3,4]
2. push() 对应 pop()
- 尾部推入/尾部弹出 会改变原数组
- 返回值 返回把指定的值添加到数组后的新长度 / 返回弹出的元素
- 举例
console.log([1].push("z")) //2
console.log([1,2,3].pop()) //3
3. unshift() 对应 shift()
- 头部推入/头部弹出 会改变原数组
- 返回值 返回把指定的值添加到数组后的新长度 / 返回弹出的元素
- 举例
console.log([1].unshift("z")) //2
console.log([1,2,3].shift()) //1
4. concat()
- 连接 连接两个或多个数组。
- 返回值 返回一个新的数组 , 不改变原数组
console.log([1].concat([2])) //[1,2]
console.log([1].concat([2],["a","b"])) //[1,2,"a","b"]
5. join()
- 把数组中的所有元素放入一个字符串 不改变原数组
- 返回值 返回一个字符串
console.log(['hello','ergou'].join('?')) //"hello?ergou"
6. sort()
- 对数组的元素进行排序 改变原数组
- 返回值 对数组的引用,数组在原数组上进行排序,不生成副本。
console.log([2,5,2,7,4].sort(
function(n1,n2){return n1-n2})
) //[2, 2, 4, 5, 7]
7. toString()
- 把数组转换为字符串,并返回结果。 不改变原数组
- 返回值 返回值与没有参数的 join() 方法返回的字符串相同
console.log(['hello',2,'狗'].toString()) //"hello,2,狗"
8. map(function(currentValue,index,arr), thisValue) es5方法
- 参数 function(currentValue,index,arr)参数必须(处理元素的方法)
- 按照原始数组元素顺序依次处理元素。 不改变原数组
- 返回值 返回一个新数组,数组中的元素为原始数组元素调用函数处理后的值
//(1)
console.log([1,2,3].map(function(item){
return item*2
})) //[2,4,6]
//(2)
//在数组 arr 中,查找值与 item 相等的元素出现的所有位置
function findAllOccurrences(arr, item) {
return arr.map(function(e, index) {
return e === item ? index : -1;
}).filter(function(i) {
return i !== -1;
/* 过滤掉 i === -1 的情况 */
})
}
findAllOccurrences([1,2,5,2,6], 2) //[1,3]
9. filter(function(currentValue,index,arr), thisValue) es5方法
- 参数 function(currentValue,index,arr)参数必须(处理元素的方法)
- 按照原始数组元素顺序依次处理元素。 不改变原数组
- 返回值 返回一个新的数组,新数组中的元素是通过检查指定数组中符合条件的所有元素
用法见map()
10. forEach(function(){item.index})
用法略略略略
另 类数组(例如arguments) 转 数组常用方法
1.定义:
- 拥有length属性,其它属性(索引)为非负整数(对象中的索引会被当做字符串来处理,这里你可以当做是个非负整数串来理解)
- 不具有数组所具有的方法
- (实际上,只要有length属性,且它的属性值为number类型就行了)
常用方法
function a(){
return Array.prototype.slice.call(arguments) //然后就可以直接使用数组方法啦
}
console.log(a('a',1,2,'b')) //["a", 1, 2, "b"]