JS数组中6个基础方法及其API

JS数组中6个基础方法及其API

1.将数组转换为字符串,两种方法:toString(),join(“separator”)

var arr=["tom","jerry","king"]; 
console.log(arr.toString());//tom,jerry,king 
console.log(arr.join("-"));//tom-jerry-king 

2.拼接一个或多个数组,并返回新的数组,concat(arr1,arr2…)

var arr1=["kate","lucy"]; 
console.log(arr1.concat(arr));//["kate","lucy","tom","jerry","king"]
 console.log(arr.concat(arr1));//["tom","jerry","king","kate","lucy"] 
 var arr1=["a"],arr2=["b"],arr3=["c"]; 
 var newArr= arr1.concat(arr2,arr3); 
 console.log(newArr);//["a","b","c"] 

3.截取数组中的元素,slice(start):

  • 1个参数(正数)时,截取从开始下标位置处的元素(包含)到末尾元素(包含)的数组;
  • 1个参数(负数)时,splice(-1)为截取最后1个元素组成的数组,splice(-arr.length)为截取所有元素组成的数组;
  • slice(start,end):2个参数(正数||负数)时,截取从开始下标位置处的元素(包含)到末尾下标元素(不包含)的数组;
    var arr=["a","b","c","d","e"]; 
    console.log(arr.slice(1));//[ 'b', 'c', 'd', 'e' ] 
    console.log(arr.slice(1,4));//[ 'b', 'c', 'd' ] 不包含arr[4]=e 
    console.log(arr.slice(-1));//[ 'e' ] 
    console.log(arr.slice(-arr.length));//[ 'a', 'b', 'c', 'd', 'e' ] 
    console.log(arr.slice(-4,-1));//[ 'b', 'c', 'd' ]不包含arr[-1]=e 

4.删除数组中的元素
splice(start,counter,item),第1个参数为起始位置处元素的下标(包含),第2个参数为要删除元素的个数,第3个参数为要添加(插入)或者替换的元素

//(1).从下标位置为2的元素开始删除2个元素 
var arr=['a','b','c','d','e','f','g','h']; 
arr.splice(2,2);console.log(arr)//[ 'a', 'b', 'e', 'f', 'g', 'h' ] 
// (2).将元素f替换为m 
arr.splice(5,1,"m");console.log(arr); 
// (3).在下标为1的位置插入元素z 
arr.splice(1,0,"z");console.log(arr); 

5.反转数组中的元素

var arr=['a','b','c','d'] 
console.log(arr.reverse());//[ 'd', 'c', 'b', 'a' ] 

6.对数组中的元素进行排序sort()

默认按照Unicode码升序(由小到大)排列,借助回调函数时可实现数字的真正的升序排列,sort(callback),此方法仅限于元素为数字的数组
升序:sort((a,b)=>{a-b}) 降序:sort((a-b)=>{b-a})

var arr=["80","10","45","6","11"]; var arr1=['d','e','a','c'];//使用sort(callback)不生效 
console.log(arr.sort());//[ '10', '11', '45', '6', '80' ] 
console.log(arr.sort((a,b)=>a-b));//升序:[ '6', '10', '11', '45', '80' ] 
console.log(arr.sort((a,b)=>b-a));//降序:[ '80', '45', '11', '10', '6' ] 
console.log(arr1.sort((a,b)=>a-b));//未生效:['d','e','a','c'] 

总结一下这6种方法的API:

(1)转换为字符串,toString() 或者join(“separator”);
(2)拼接数组concat(arr1,arr2,…);
(3)截取数组中的元素,slice(start,end);
(4)删除,替换,添加数组splice(start,counter,item);
(5)反转数组,reverse();
(6)对数组中的元素进行排序,sort()和sort(callback)。(001/100)