数组的常用方法

1、toString

将数组转换成字符串

var arr = ["red", "blue", "green"];
console.log(arr.toString());	//red,blue,green

运行结果:red,blue,green以逗号分隔的字符串

2、join

将所有数组元素结合为一个字符串,可以自定义分隔符

var arr = ["red", "blue", "green"];
console.log(arr.join(":"));	//red:blue:green

3、unshift

向数组的开头添加新元素

var arr = ["red", "blue", "green"];
arr.unshift("abc");
console.log(arr);	//['abc', 'red', 'blue', 'green']

4、push

向数组末尾添加新元素

var arr = ["red", "blue", "green"];
arr.push("abc");
console.log(arr);	//['red', 'blue', 'green', 'abc']

5、pop

从数组中删除最后一个元素

var arr = ["red", "blue", "green"];
arr.pop();
console.log(arr);	//['red', 'blue']

6、shift

删除数组首个元素,并把所有其他元素向前位移

var arr = ["red", "blue", "green"];
arr.shift();
console.log(arr);	//['blue', 'green']

7、splice

对数组进行修改操作

//删除数组
var arr = ["red", "blue", "green"];
arr.splice(1, 2);	//从索引为1开始删除2个元素
console.log(arr);	//['red']

//替换元素
var arr = ["red", "blue", "green"];
arr.splice(1, 1, "abc");	//从索引为1开始删除1个元素(blue)并使用"abc"作为新元素替换该位置
console.log(arr);	//['red', 'abc', 'green']

8、slice

返回一个新的数组,包含从start到end(不包含该元素)的数组

var arr = ["red", "blue", "green"];
var newArr = arr.slice(1, 2);	//从索引为1开始获取2个元素(不包含第二个,所以实际只获取1个元素)
console.log(newArr);	//['blue']

9、concat

连接两个或多个数组

var arr1 = [1, 2, 3];
var arr2 = [4, 5, 6];
var arr3 = arr1.concat(arr2);
console.log(arr3);	//[1, 2, 3, 4, 5, 6]

10、sort

对数组排序

var arr = [1 ,33, 23, 5, 7, 98, 3];
arr.sort();
console.log(arr);	//[1, 23, 3, 33, 5, 7, 98]	他不是按照数字大小来排序,按首字符的顺序来排序

11、reverse

颠倒数组

var arr = [1 ,33, 23, 5, 7, 98, 3];
arr.reverse();
console.log(arr);	//[3, 98, 7, 5, 23, 33, 1]

你可能感兴趣的:(前端学习笔记,javascript,前端,开发语言)