数组操作

数组操作_第1张图片
Array.png

concat

let [arr1,arr2] = [[1,2,3],[3,4,5]];
let array = arr1.concat(arr2);
console.log(array,arr1,arr2);
// [1, 2, 3, 3, 4, 5] [1, 2, 3] [3, 4, 5]
// 也用做数组深拷贝(深复制,深克隆...),该方法不会改变现有的数组,而仅仅会返回被连接数组的一个副本

join 数组转字符串

let [arr1,arr2] = [[1,2,4,5],[2,3]];
let str1 = arr1.join(arr2);
console.log(str1, arr1, arr2);
// 12,322,342,35  [1, 2, 4, 5]  [2, 3]
let [arr3,arr4] = [['你'],['好']];
let str2 = arr3.join(arr4);
console.log(str2, arr3, arr4);
// 你 ["你"] ["好"]
let arr = new Array(3)
arr[0] = "George"
arr[1] = "John"
arr[2] = "Thomas"
console.log(arr.join(' '));
// George John Thomas
console.log(arr.join());
// George,John,Thomas

pop 删除并返回数组的最后一个元素

let arr = [1,2,3,4,5];
console.log(arr.pop(),arr);
//5  [1, 2, 3, 4]

push

let arr = [1,2,3,4];
console.log(arr.push(5),arr)    
//5  [1, 2, 3, 4, 5]

reverse

let arr = [1,2,3,'n','m',{age:18,name:'hao'}]
console.log(arr.reverse(),arr);  
//[{age: 18, name: "hao"}, "m", "n", 3, 2, 1]   [{age: 18, name: "hao"}, "m", "n", 3, 2, 1]  

shift

let arr = [1,2,3,4];
console.log(arr.shift(),arr)    
// 1  [2, 3, 4]

slice

let arr = [1,2,3,4,5];
let str = 'abcdefg'
console.log(arr.slice(1,3),arr,str.slice(1,3),str);
// [2, 3]  [1, 2, 3, 4, 5] "bc" "abcdefg"
// 既可以操作数组又可以操作字符串,并且不会修改原值

sort

let arr = [1,2,3,4,5,6,23,45,55];
console.log(arr.sort(),arr);
// [1, 2, 23, 3, 4, 45, 5, 55, 6]  [1, 2, 23, 3, 4, 45, 5, 55, 6]
console.log(arr.sort((a,b)=> a-b ))
// [1, 2, 3, 4, 5, 6, 23, 45, 55]
let str = ['asd','dfg','daa','css','g','f'];
console.log(str.sort(), str.sort((a,b)=> b-a))
//  ["asd", "css", "daa", "dfg", "f", "g"]   ["asd", "css", "daa", "dfg", "f", "g"]

splice

let arr = [1,2,3,4,5,6];
console.log(arr.splice(2,3),arr);   
// [3, 4, 5]  [1, 2, 6] 

toSource

//只有 Gecko 核心的浏览器(比如 Firefox)支持该方法,也就是说 IE、Safari、Chrome、Opera 等浏览器均不支持该方法。
function employee(name,job,born){
    this.name = name;
    this.job = job;
    this.born = born;
}    
let bill = new employee('Bill Gates','Engineer',1985);
console.log(bill.toSource());
//({name:"Bill Gates", job:"Engineer", born:1985}) 

toString

let arr = [2,3,4,5,6];
console.log(arr.toString(),arr.toString('-'));
// 2,3,4,5,6    2,3,4,5,6  

toLocaleString

let arr = [2,3,4,5,6];
console.log(arr.toLocaleString());
// 2,3,4,5,6  

unshift

let arr1 = [1,2,3,4,5];
let arr2 = [1,2,3,4,5];
console.log(arr1.unshift(),arr1,arr2.unshift('3'),arr2)    
//5  [1, 2, 3, 4, 5] 6  ["3", 1, 2, 3, 4, 5]

valueof

let arr = [1,2,3,4,5];
console.log(arr.valueof(),arr);    
//Uncaught TypeError: arr.valueof is not a function

你可能感兴趣的:(数组操作)