您当前的位置: 首页 > 学无止境 > JS经典实例 网站首页JS经典实例
ES5_数组的扩展
发布时间:2019-10-05 17:48:16编辑:雪饮阅读()
indexOf
在数组中用于返回该数组中某个元素第一次出现的下标
var arr=[2,4,2,3,5];
console.log(arr.indexOf(2));
lastIndexOf
在数组中用于返回该数组中某个元素最后一次出现的下标
var arr=[2,4,2,3,5];
console.log(arr.lastIndexOf(2));
forEach
用于遍历数组
var arr=[2,4,2,3,5];
arr.forEach(function(item,index){
console.log(item,index);
});
map
用于遍历数组,且能返回新数组
var arr=[2,4,2,3,5];
var newArr=arr.map(function(item,index){
return item+10;
});
console.log(newArr);
该示例将arr数组的每个元素值加了10个单位后返回一个新的newArr数组
filter:
用于遍历数组,且返回新数组(对每个元素遍历时其操作为true的元素集合)
var arr=[2,4,2,3,5];
var newArr=arr.filter(function(item,index){
return item>3;
});
console.log(newArr);
该示例从arr数组中找到值大于3的元素集合形成newArr数组
关键字词:indexOf,lastIndexOf,forEach,map,filter