创建数组
创建数组有两种方式
方式1:关键字形式
var array = new Array();
方式2:字面量形式
var array = [];//常用
var array = [1,2,3,"hell"];
数组中的元素类型可以不同
var students = [
{id:1, score:80},
{id:2, score:46},
{id:3, socre:36}
];
arr.length
获取数组长度,表示数组有多少个元素
获取数组元素
var students = [
{id:1,score:80},
{id:2,score:25},
{id:3,scroe:67}
] ;
students[o];//{id:1,score:80}
students[o].score;// 80;
修改数组元素
var students = [
{id:1,score:80},
{id:2,score:25},
{id:3,scroe:67}
] ;
students[0].score = 90;//修改
查找数组中的元素
arr.indexOf(searchElement[,fromIndex=0])
查找searchElement参数传入的字符,找到返回索引值否则返回-1.
var telephones = [110 120, 114];
telephones.indexOf(120);//1
telephones.indexOf(119);//不存在返回-1
arr.forEach(callback[, thisArg])
var students = [
{id:1, scroe:80},
{id:2, scroe:50},
{id:3, score:50}
]
var editScore = function(item){
item.score += 5;
};
students.forEach(editScore);//遍历数组students,并给score属性+5;
将数组内元素顺序倒置
arr.reverse()
var students =[
{id:1, score:80},
{id:2, score:35},
{id:3, score:37}
];
students.reverse();
students[0].score;//37
数组中的排序
arr.sort([compareFunction])
compareFunction:传入一个设定比较方法的回调函数
var students =[
{id:1, score:80},
{id:2, score:35},
{id:3, score:37}
];
var byScore = function(a,b){
return b.score-a.score;
}//如果b.score-a.score小于0,则排序a前b后
students.sort(byScore);
注意arr.sort()方法会直接改变数组元素
在已有的数组结尾处加入元素
var students =[
{id:1, score:80},
{id:2, score:35},
{id:3, score:37},
];
students.push({id:4,score:90},{id:5,score:57});
那么数组为:
var students =[
{id:1, score:80},
{id:2, score:35},
{id:3, score:37},
{id:4,score:90},
{id:5,score:57}
];
在已有的数组开始位置加入元素
var students =[
{id:1, score:80},
{id:2, score:35},
{id:3, score:37}
];
students.unshift({id:4,score:90},{id:5,score:57});
那么数组为:
var students =[
{id:5,score:57},
{id:4,score:90},
{id:1, score:80},
{id:2, score:35},
{id:3, score:37}
];
获取第一个元素并在数组中删除这个元素
arr.shift
var students =[
{id:1, score:80},
{id:2, score:35},
{id:3, score:37}
];
students.shift();//{id:1, score:80}
数组变为
students =[
{id:2, score:35},
{id:3, score:37}
];
获取数组最后一个元素并把它从数组中删除
* arr.pop()*
var students =[
{id:1, score:80},
{id:2, score:35},
{id:3, score:37}
];
students.pop();//{id:3, scroe:37}
数组改变为:
students =[
{id:1, score:80},
{id:2, score:35}
];
在数组任意位置插入或删除元素
arr.splice(index, howMany[,ele1[,…[,eleN]]])
index—–开始的索引位置,能取到。
howMany——需要删除元素的数量
ele—–元素
var students =[
{id:1, score:80},
{id:2, score:35},
{id:3, score:37}
];
//删除指定元素
students.splice(1);//只传索引值,将删除相应位置的元素
//插入元素
students.splice(1,0,{id:4,score:89})//删除的数量为0,则说明不删除,只插入。插入元素到索引位置的上一个位置
//删除并插入元素
students.splice(1,1,{id:5,score:34});//从索引值为1的元素开始删除,删除量为1,并插入元素{id:5, score:34}
拷贝数组中的一段
arr.slice(begin[,end])
begin—-包含
end—–不包含
var students =[
{id:1, score:80},
{id:2, score:35},
{id:3, score:37}
];
//拷贝一部分
var newStudents1 = students.slice(0,2);//拷贝了{id:1, score:80},{id:2, score:35}
//全部拷贝
var newStudent2 = students.slice(0);//只传入begin起始值,则会将后面的元素都拷贝。
字符的连接
arr.concat(value1,…[,valueN])
value值不一定是数组,也可以是其他值
字符的分割和拼接
分割字符存储为数组
将数组拼接为特定字符串
arr.join([separator])
separator—-为设置的特定字符。
arr.reduce(callback,[initialValue])