JS数组处理

1.arr.toSring() => 数组转为字符串

var arr = [1,2,3];

arr.toSring();

// arr => “1,2,3”

2.arr.join("-") = > 数组以分隔符转为字符串

var arr = [1,2,3];

arr.join("+");

//arr =>  "1+2+3"

3.arr.pop() => 删除数组中最后一个元素(返回已删除的元素)

var arr = [1,2,3];

var last = arr.pop();

// last => 3

// arr => [1,2]

4.arr.push("lastValue")  => 向数组末尾添加一个新元素(返回新数组的长度)

var arr = [1,2];

var length = arr.push(3);

//arr => [1,2,3]

//length => 3

5.arr.shift() => 删除数组中的首个元素(返回已删除的元素)

var arr = [1,2,3];

var first = arr.shift();

//arr => [2,3]

//first => 1

6.arr.unshift("fistValue") => 在数组开头添加一个新元素(返回新数组的长度)

var arr = [1,2,3];

var length = arr.unshift(0);

//arr  => [0,1,2,3]

//length => 4

7.arr[arr.length] = "lastValue" 通过索引(下标)访问/修改数组

var arr = [0,1,2,3];

var first = arr[0];

arr[3] = 4;

arr[arr.length]  = "last"

//fist => 0

//arr[3] => 4

//arr => [0,1,2,4]

//arr = > [0,1,2,4,"last"]

8. delete arr[index] => 根据数组下标删除元素(返回true)

var arr = [0,1,2,4,"last"];

var  empty  = delete arr[3];

//empty => true

//arr => [0,1,2,empty,"last"]

9.splice(index,deleteNum,addValue)   => 根据下标添加/删除数组(返回已删除的)

addValue : 添加新元素,可省略

var arr = [1,2,3]

var delete = arr.splice(1,1,"last");   

//从数组下标为1开始删除1个,添加"last"

//delete =>  [2]

//arr => [1,"last",3]

10.newArr = arr3.concat(arr1,arr2) => 合并/连接数组(不更改原数组,返回新数组)

arr1 = [1,2,3];

arr2 = [4,5,6]

arr3 = [7,8,9];

newArr = arr3.concat(arr1,arr2,[1,2]);

//newArr  => [7,8,9,1,2,3,4,5,6,1,2]

11.var cutDate = slice(start,end) =>  返回选取下标之间的新数组,不包含end下标元素,不修改原数组,可省略end参数,默认选取到最后。

arr1 = [1,2,3];

sliceData = [1];

//sliceDate => 1

12.sort() => 以字母由a-z/数字由0到9顺序对数组进行排序

arr = [1,3,2];

arr.sort();

//arr => [1,2,3]

arr1 = ["g","e","a"];

arr1.sort();

//arr1 => ["a","e","g"]

如果数字按照字符串来排序,则 "25" 大于 "100",因为 "2" 大于 "1"。

可{比值函数}来修正此问题:

//原理

当 sort() 函数比较两个值时,会将值发送到比较函数,并根据所返回的值(负、零或正值)对这些值进行排序。 

//升序

var points = [40, 100, 1, 5, 25, 10];

points.sort(function(a, b){return a - b});

//如果返回负值则把a排在b前面

// points[0] => 最低值

// points[points.length-1] => 最高值


//降序

var points = [40, 100, 1, 5, 25, 10];

points.sort(function(a, b){return b - a});

//如果返回负值则把a排在b前面 

// points[0] => 最高值 

// points[points.length-1] => 最低值


//以随机顺序排序数组

var points = [40, 100, 1, 5, 25, 10];

points.sort(function(a, b){return 0.5 - Math.random()});

13.reverse() => 反转数组中的元素

arr = [1,3,2];

arr.reverse ();                                                                            

//arr=> [2,3,1];

arr.reverse();

//arr => [1,3,2]

14.查找数组中的最高/最小值

max = Math.max.apply(null,arr)

min = Math.min.apply(null,arr)

你可能感兴趣的:(JS数组处理)