数组
数组常用方法
方法名 | 含义 |
reverse() | 将数组元素倒序排列 |
indexOf() | 查询指定元素第一出现的位置 |
lastIndexOf() | 查询指定元素最后一次的位置 |
join() | 拼接为字符串 |
concat() | 将多个组拼接成一个数组 |
push() | 向数组末尾添加新的元素 |
pop() | 删除并返回数组的最后一个元素 |
unshift() | 向数组开头添加新的元素,返回新的数组长度 |
shift() | 删除并返回数组的第一个元素 |
slice() | 获取指定索引范围内的元素 |
splice() | 从指定索引位置删除并添加新的内容 |
toString() | 将数组转换为字符串 |
valueOf() | 返回数组本身,会自动调用 |
sort()排序 | 默认按字符编码ASCII的顺序排序,可自定义规则 |
forEach() | 遍历数组 |
//1. reverse() 将数组元素倒序排序
用法: 数组名.方法名(参数)
var nums=[12,4,5,6,42,68,4,77]
console.log(nums);
nums.reverse();
console.log(nums);
//2. indexOf() 查询指定元素第一出现的位置
//3. lastIndexOf()查询指定元素最后一次的位置
var names = ['John','Lilly','Make','Job','Jack','John','Merry'];
console.log(names);
console.log(names.indexOf('John'));
console.log(names.lastIndexOf('John'));
//4. join()拼接为字符串
console.log(names.join());
console.log(names.join('-'));
//5. concat() 将多个组拼接成一个数组
var sex = ['male','female','male','male','male','male']
names = names.concat(sex);
console.log(names);
//6. push() 向数组末尾添加新的元素
names.push('Merry');
console.log(length);
//7. pop() 删除并返回数组的最后一个元素
names.pop('John');
console.log(names);
//8. unshift() 向数组开头添加新的元素,返回新的数组长度
names.unshift('A','B','C')
console.log(names);
//9. shift() 删除并返回数组的第一个元素;
names.shift('John');
console.log(names);
//10. slice() 返回数组中指定范围内的元素(获取指定索引范围内的元素)
console.log(names.slice(2));
//11. splice() 从指定索引位置删除并添加新的内容
names.splice(2,3); // 从索引为2的位置开始删除,删除3个;
names.splice(2,3,'A','B'); //在删除的位置添加元素‘A’,‘B’
console.log(names);
//12. toString() 将数组转换为字符串
var str = names.toString();
console.log(str);
//13. valueOf() 返回数组本身,会自动调用
console.log(names.values());
console.log(names);
//14. sort()排序,默认按字符编码ASCII的顺序排序,可自定义规则
var nums = [12,4,5,9,92,64,18,8];
//升序
function ShengXu(a,b){
return a-b;
}
//降序
function JiangXu(a,b){
return b-a;
}
nums.sort(ShengXu);
nums.sort(JiangXu);
console.log(nums);
//15. forEach() 遍历数组
names.forEach(function(value,index){
console.log(value,index);
});