如下方法添加到了Array.prototype对象上(isArray除外)数组
相似字符串的indexOf()方法浏览器
stringObject.indexOf(searchvalue,fromindex)
var data = [2, 5, 7, 3, 5]; console.log(data.indexOf(5, "x")); // 1 ("x"被忽略) console.log(data.indexOf(5, "3")); // 4 (从3号位开始搜索) console.log(data.indexOf(4)); // -1 (未找到) console.log(data.indexOf("5")); // -1 (未找到,由于5 !== "5")
相似indexOf()方法(顺序相反)函数
Array在ES5新增的方法中,参数都是function类型,默认有传参(遍历的数组内容,对应的数组索引,数组自己)this
[].forEach(function(value, index, array) { // ... });
forEach方法 遍历数组元素prototype
var colors = ['red', 'green', 'blue']; colors.forEach(function(color) { console.log(color); });
forEach除了接受一个必须的回调函数参数,还能够接受一个可选的上下文参数(改变回调函数里面的this指向)(第2个参数)若是这第2个可选参数不指定,则使用全局对象代替(在浏览器是为window),严格模式下甚至是undefinedcode
array.forEach(callback,[ thisObject])
映射(一一对应)。[].map();基本用法跟forEach方法相似:对象
array.map(callback,[ thisObject]);
可是callback须要有return值(若是没有,就像会返回undefined)索引
var a1 = ['a', 'b', 'c']; var a2 = a1.map(function(item) { return item.toUpperCase(); }); console.log(a2); // logs A,B,C
过滤筛选(callback在这里担任的是过滤器的角色,当元素符合条件,过滤器就返回true,而filter则会返回全部符合过滤条件的元素)。字符串
array.filter(callback,[ thisObject]);
指数组filter后,返回过滤后的新数组。用法跟map类似回调函数
var a1 = ['a', 10, 'b', 20, 'c', 30]; var a2 = a1.filter(function(item) { return typeof item == 'number'; }); console.log(a2); // logs 10,20,30
every(callback[, thisObject])当数组中每个元素在callback上被返回true时就返回true。
function isNumber(value){ return typeof value == 'number'; } var a1 = [1, 2, 3]; console.log(a1.every(isNumber)); // logs true var a2 = [1, '2', 3]; console.log(a2.every(isNumber)); // logs false
some(callback[, thisObject]) 只要数组中有一项在callback上被返回true,就返回true。
function isNumber(value){ return typeof value == 'number'; } var a1 = [1, 2, 3]; console.log(a1.some(isNumber)); // logs true var a2 = [1, '2', 3]; console.log(a2.some(isNumber)); // logs true var a3 = ['1', '2', '3']; console.log(a3.some(isNumber)); // logs false
对数组中的全部元素调用指定的回调函数。
该回调函数的返回值为累积结果,而且此返回值在下一次调用该回调函数时做为参数提供。
var a = [10, 20, 30]; var total = a.reduce(function(first, second) { return first + second; }, 0); console.log(total) // Prints 60
reduce的做用彻底相同,惟一的不一样是,reduceRight是从右至左遍历数组的元素。
Array.isArray直接写在了Array构造器上,而不是prototype对象上。
Array.isArray会根据参数的[[Class]]内部属性是不是”Array”返回true或false.
Array.isArray("NO U") falseArray.isArray(["NO", "U"])// true
真实数组具备slice方法,能够对数组进行浅复制(不影响原数组),返回的依然是数组。
相似数组虽然有length属性,可使用for循环遍历,却不能直接使用slice方法,会报错!可是经过Array.prototype.slice.call则不会报错,自己(相似数组)被从头至尾slice复制了一遍——变成了真实数组!
将相似数组的对象(好比arguments)转换为真实的数组
Array.prototype.slice.call(arguments)