一、数组转字符串
需要将数组元素用某个字符连接成字符串。
var a=[1,2,3,4,5,6]; var b=a.join(','); console.log(b);
输出:1,2,3,4,5,6
二、字符串转数组
实现方法为将字符串按某个字符切割成若干个字符串,并以数组形式返回
var a = "abc,abcd,aaa"; var b= a.split(",");// 在每个逗号(,)处进行分解。 console.log(b);
输出:["abc", "abcd", "aaa"]
三、数组去重
Array.prototype.duplicateRemoval = function () { var n = []; //一个新的临时数组 for (var i = 0; i < this.length; i++) //遍历当前数组 { //如果当前数组的第i已经保存进了临时数组,那么跳过, //否则把当前项push到临时数组里面 if (n.indexOf(this[i]) == -1) n.push(this[i]); } return n; } var a=[1,1,2,2,3,4,5,5,7,7]; a.duplicateRemoval();
输出: [1, 2, 3, 4, 5, 7]
Array 对象方法
concat()
连接两个或更多的数组,并返回结果。
var arr1=["张三","李四","王五"]; var arr2=["Tom","Jack","TM"]; arr1.concat(arr2);
输出:["张三", "李四", "王五", "Tom", "Jack", "TM"]
join()
把数组的所有元素放入一个字符串。元素通过指定的分隔符进行分隔。
var arr1=["张三","李四","王五"]; var arr2=arr1.join(','); console.log(arr2);
输出:张三,李四,王五
pop()
删除并返回数组的最后一个元素
var arr1=["张三","李四","王五"]; arr1.pop(); console.log(arr1);
输出:["张三", "李四"]
push()
向数组的末尾添加一个或更多元素,并返回新的长度。
var arr1=["张三","李四","王五"]; arr1.push("赵六"); console.log(arr1);
输出: ["张三", "李四", "王五", "赵六"]
reverse()
颠倒数组中元素的顺序。
var arr1=["张三","李四","王五"]; var arr2=arr1.reverse(); console.log(arr2);
输出:["王五", "李四", "张三"]
shift()
删除并返回数组的第一个元素
var arr1=["张三","李四","王五"]; arr1.shift(); console.log(arr1);
输出:["李四", "王五"]
slice()
从某个已有的数组返回选定的元素
var arr1=["张三","李四","王五"]; var arr2=arr1.slice(1,2); console.log(arr2);
输出:["李四"]
sort()
对数组的元素进行排序
var arr1 = [11,2,28,4,5,1]; var arr2 = arr1.sort(function(a,b){ return a-b; }) console.log(arr2);
输出:[1, 2, 4, 5, 11, 28]
splice()
删除元素,并向数组添加新元素。
var arr1=["张三","李四","王五"]; var arr2=arr1.splice(1,1,"赵六"); console.log(arr1);
输出:["张三", "赵六", "王五"]
toString()
把数组转换为字符串,并返回结果。
var arr1=["张三","李四","王五"]; var arr2=arr1.toString(); console.log(arr2);
输出:张三,李四,王五
toLocaleString()
把数组转换为本地字符串,并返回结果
var arr1=["张三","李四","王五"]; var arr2=arr1.toLocaleString(); console.log(arr2);
输出:张三,李四,王五
unshift()
向数组的开头添加一个或更多元素,并返回新的长度。
var arr1=["张三","李四","王五"]; arr1.unshift("第一个"); console.log(arr1);
输出:["第一个", "张三", "李四", "王五"]
valueOf()
返回数组对象的原始值
var arr1=["张三","李四","王五"]; var arr2=arr1.valueOf(); console.log(arr2);
输出: ["张三", "李四", "王五"]