ES5对数组Array扩展了以下方法。
- Array.prototype.indexOf(value) 在数组中找出第一个值等于value的元素的下标。
- Array.prototype.lastIndexOf(value) 找出最后一个值等于value的元素的下标。
- Array.prototype.forEach(function (item,index) {}) 遍历数组。
- Array.prototype.map(function (item,index) {}) 遍历数组,返回经过内部方法处理之后的新数组。
- Array.prototype.filter(function (item,index) {}) 遍历数组,返回经过内部方法处理之后的新数组。当内部方法返回true时,才加入到新数组中。
注意这些方法都是增加贼显示原型prototype上了。也就是所有的array对象都有这些方法。
例子:
<script type="text/javascript">
var arr = [2,6,7,8,9,12,23,6,4];
console.log(arr.indexOf(6)); //输出 1
console.log(arr.lastIndexOf(6)); //输出 7
//遍历输出
arr.forEach(function (item,index) {
console.log(item,index);
});
//把每个元素加100,后得到新的数组
var mapArr = arr.map(function (item,index) {
return item + 100;
})
console.log(mapArr);
//把大于10的元素组成新的数组
var filterArr = arr.filter(function (item,index) {
return item >10;
})
console.log(filterArr);
</script>