slice(begin,end)
从事过数组中提取指定的一个或多个元素,返回结果为新的数组(不会改变原来的数组)
slice(begin,end)包含begin不包含end
let animous = ['cat','dog','brid','pig']
console.log(animous.slice(1,2))
// 结果为[ 'dog' ]
可以使用slice将伪数组转化为真数组,Array.slice()会创建一个新的数组
arr = Array.prototype.slice.call(arrayLike)
arr2 = [].slice.call(arrayLike)
function abc() {
console.log(arguments)
let newArray = Array.prototype.slice.call(arguments)
console.log(newArray)
}
abc(1,2,3,4,5)
// 结果为[Arguments] { '0': 1, '1': 2, '2': 3, '3': 4, '4': 5 }
[ 1, 2, 3, 4, 5 ]
splice(索引值,删除数量,添加内容)
从数组中删除指定的一个或多个元素,返回结果为新的数组,改变原数组
console.log(animous.splice(1,1),animous)
animous.splice(1,0,'dog')
console.log(animous)
// 结果为[ 'cat', 'brid', 'pig' ]
concat()
连接两个数组,返回新的数组,不会改变原数组
let arr3 = ['hello','world','my','hhh']
let arr4 = ['black','white','red']
console.log(arr3.concat(arr4))
// 结果为[
'hello', 'world',
'my', 'hhh',
'black', 'white',
'red'
]
join()
将数组转换成字符串
let str = arr3.join(',')
console.log(str)
//结果为hello,world,my,hhh
reverse()
反转数组,返回结果为反转后的数组(会改变原来的数组)
arr4.reverse()
console.log(arr4)
//结果为[ 'red', 'white', 'black' ]
sort()
如果在使用sort()方法时不带参数,则默认按照Unicode编码,从小到大排序
let arr5 = [1,2,123,34,24,224]
let result = arr5.sort()
console.log(result)
//结果为[ 1, 123, 2, 224, 24, 34 ]
顺序排列,返回1会交换位置,返回-1不变
// 从小到大排列
let fn = function(a,b) {
if(a>b){
return 1
}else{
return -1
}
}
let newArr2 = arr5.sort(fn)
console.log(newArr2)
// 结果为[ 1, 2, 24, 34, 123, 224 ]