javascript Array Methods(学习笔记)
ECMAScript 5 定义了9个新的数组方法,分别为:
1.forEach(); 2.map(); 3.filter(); 4.every(); 5.some(); 6.reduce(); 7.reduceRight(); 8.indexOf(); 9.lastIndexOf();
概述:首先,大多数的方法都接受一个函数作为第一个参数,并为数组里的每个元素(或者一些元素)执行这个函数.在稀疏数组中(索引不以0开始,并且元素不连续),不存在的数组元素不调用函数参数.大多数实例中,定义的函数(方法中的参数)包含三个参数:第一个是元素的值,第二个是元素的索引,第三个是数组本身.ECMAScript 5 数组方法不改变调用它们的数组,但是我们自己定义的函数可能会改变数组的值.接下来分别介绍具体方法:
forEach():
为数组中的每个元素执行指定操作.
array1.forEach(callbackfn[, thisArg])
参数:
参数 |
定义 |
---|---|
array1 |
必选。 一个数组对象。 |
callbackfn |
必选。 最多可以接受三个参数的函数。 对于数组中的每个元素,forEach 都会调用 callbackfn 函数一次。 |
thisArg |
可选。 callbackfn 函数中的 this 关键字可引用的对象。 如果省略 thisArg,则 undefined 将用作 this 值。 |
参数
如果callback参数不是函数对象,则将引发TypeError异常.
备注:
对于数组中出现的每个元素,forEach 方法都会调用 callbackfn 函数一次(采用升序索引顺序)。 将不会为数组中缺少的元素调用回调函数。
除了数组对象之外,forEach 方法可由具有 length 属性且具有已按数字编制索引的属性名的任何对象使用。
回调函数语法:
function callbackfn(value, index, array1)
你可使用最多三个参数来声明回调函数。
prototype源码: (来源于官方文档)
// Production steps of ECMA-262, Edition 5, 15.4.4.18
// Reference: http://es5.github.io/#x15.4.4.18
if (!Array.prototype.forEach) { Array.prototype.forEach = function(callback, thisArg) { var T, k; if (this == null) {
throw new TypeError(' this is null or not defined');
} // 1. Let O be the result of calling ToObject passing the |this| value as the argument.
var O = Object(this); // 2. Let lenValue be the result of calling the Get internal method of O with the argument "length".
// 3. Let len be ToUint32(lenValue).
var len = O.length >>> 0; // 4. If IsCallable(callback) is false, throw a TypeError exception.
// See: http://es5.github.com/#x9.11
if (typeof callback !== "function") {
throw new TypeError(callback + ' is not a function');
} // 5. If thisArg was supplied, let T be thisArg; else let T be undefined.
if (arguments.length > 1) {
T = thisArg;
} // 6. Let k be 0
k = 0; // 7. Repeat, while k < len
while (k < len) { var kValue; // a. Let Pk be ToString(k).
// This is implicit for LHS operands of the in operator
// b. Let kPresent be the result of calling the HasProperty internal method of O with argument Pk.
// This step can be combined with c
// c. If kPresent is true, then
if (k in O) { // i. Let kValue be the result of calling the Get internal method of O with argument Pk.
kValue = O[k]; // ii. Call the Call internal method of callback with T as the this value and
// argument list containing kValue, k, and O.
callback.call(T, kValue, k, O);
}
// d. Increase k by 1.
k++;
}
// 8. return undefined
};
}
具体应用如下:
1 //defined the callback function
2 function showResult(val,index,arr){
3 document.write("value:"+val);
4 document.write("index:"+index);
5 document.write("<br />");
6 }
7
8 //defined an array and assignment two values
9 var arrays = ["hello","world"];
10
11 //invoked
12 arrays.forEach(showResult)
13
14 //output
15 value:hello index:0
16 value:world index:1
map():
对数组的每个元素调用定义的回调函数并返回包含结果的数组.
注意:用法,参数和forEach()相似,但是map()要返回一个结果数组.参考上面forEach()的用法.直接上源码:
// Production steps of ECMA-262, Edition 5, 15.4.4.19
// Reference: http://es5.github.io/#x15.4.4.19
if (!Array.prototype.map) { Array.prototype.map = function(callback, thisArg) { var T, A, k; if (this == null) {
throw new TypeError(' this is null or not defined');
} // 1. Let O be the result of calling ToObject passing the |this|
// value as the argument.
var O = Object(this); // 2. Let lenValue be the result of calling the Get internal
// method of O with the argument "length".
// 3. Let len be ToUint32(lenValue).
var len = O.length >>> 0; // 4. If IsCallable(callback) is false, throw a TypeError exception.
// See: http://es5.github.com/#x9.11
if (typeof callback !== 'function') {
throw new TypeError(callback + ' is not a function');
} // 5. If thisArg was supplied, let T be thisArg; else let T be undefined.
if (arguments.length > 1) {
T = thisArg;
} // 6. Let A be a new array created as if by the expression new Array(len)
// where Array is the standard built-in constructor with that name and
// len is the value of len.
A = new Array(len); // 7. Let k be 0
k = 0; // 8. Repeat, while k < len
while (k < len) { var kValue, mappedValue; // a. Let Pk be ToString(k).
// This is implicit for LHS operands of the in operator
// b. Let kPresent be the result of calling the HasProperty internal
// method of O with argument Pk.
// This step can be combined with c
// c. If kPresent is true, then
if (k in O) { // i. Let kValue be the result of calling the Get internal
// method of O with argument Pk.
kValue = O[k]; // ii. Let mappedValue be the result of calling the Call internal
// method of callback with T as the this value and argument
// list containing kValue, k, and O.
mappedValue = callback.call(T, kValue, k, O); // iii. Call the DefineOwnProperty internal method of A with arguments
// Pk, Property Descriptor
// { Value: mappedValue,
// Writable: true,
// Enumerable: true,
// Configurable: true },
// and false. // In browsers that support Object.defineProperty, use the following:
// Object.defineProperty(A, k, {
// value: mappedValue,
// writable: true,
// enumerable: true,
// configurable: true
// }); // For best browser support, use the following:
A[k] = mappedValue;
}
// d. Increase k by 1.
k++;
} // 9. return A
return A;
};
}
具体实现:
//defined callback function
function AreaOfCircle(radius){
var res = Math.PI(radius*radius);
return res.toFixed(0);
} //defined the array and assignment
var arr = [10,20,30]; //invoked
var arrlist = arr.map(AreaOfCircle); //output
document.write(arrlist); 314,1257,2827
filter():
返回数组中的满足回调函数中指定的条件的元素.
filter()方法的参数也如上,不过区别在于它返回一个包含回调函数为其返回 true 的所有值的新数组。 如果回调函数为 array1 的所有元素返回 false,则新数组的长度为 0。
prototype源码:
if (!Array.prototype.filter) {
Array.prototype.filter = function(fun/*, thisArg*/) {
'use strict'; if (this === void 0 || this === null) {
throw new TypeError();
} var t = Object(this);
var len = t.length >>> 0;
if (typeof fun !== 'function') {
throw new TypeError();
} var res = [];
var thisArg = arguments.length >= 2 ? arguments[1] : void 0;
for (var i = 0; i < len; i++) {
if (i in t) {
var val = t[i]; // NOTE: Technically this should Object.defineProperty at
// the next index, as push can be affected by
// properties on Object.prototype and Array.prototype.
// But that method's new, and collisions should be
// rare, so use the more-compatible alternative.
if (fun.call(thisArg, val, i, t)) {
res.push(val);
}
}
} return res;
};
}
具体实现:
// Define a callback function.
function CheckIfPrime(value, index, ar) {
high = Math.floor(Math.sqrt(value)) + 1; for (var div = 2; div <= high; div++) {
if (value % div == 0) {
return false;
}
}
return true;
} // Create the original array.
var numbers = [31, 33, 35, 37, 39, 41, 43, 45, 47, 49, 51, 53]; // Get the prime numbers that are in the original array.
var primes = numbers.filter(CheckIfPrime); document.write(primes);
// Output: 31,37,41,43,47,53
以上资料整理官方文档和javascript权威指南
javascript Array Methods(学习笔记)的更多相关文章
- 7 种 Javascript 常用设计模式学习笔记
7 种 Javascript 常用设计模式学习笔记 由于 JS 或者前端的场景限制,并不是 23 种设计模式都常用. 有的是没有使用场景,有的模式使用场景非常少,所以只是列举 7 个常见的模式 本文的 ...
- JavaScript 权威指南-学习笔记(一)
本文所有教程及源码.软件仅为技术研究.不涉及计算机信息系统功能的删除.修改.增加.干扰,更不会影响计算机信息系统的正常运行.不得将代码用于非法用途,如侵立删! ## JavaScript 权威指南-学 ...
- [Javascript ] Array methods in depth - sort
Sort can automatically arrange items in an array. In this lesson we look at the basics including how ...
- ArcGIS API for JavaScript 4.2学习笔记[0] AJS4.2概述、新特性、未来产品线计划与AJS笔记目录
放着好好的成熟的AJS 3.19不学,为什么要去碰乳臭未干的AJS 4.2? 4.2全线基础学习请点击[直达] 4.3及更高版本的补充学习请关注我的博客. ArcGIS API for JavaScr ...
- JavaScript Array methods performance compare
JavaScript Array methods performance compare JavaScript数组方法的性能对比 env $ node -v # v12.18.0 push vs un ...
- JavaScript权威设计--JavaScript函数(简要学习笔记十一)
1.函数调用的四种方式 第三种:构造函数调用 如果构造函数调用在圆括号内包含一组实参列表,先计算这些实参表达式,然后传入函数内.这和函数调用和方法调用是一致的.但如果构造函数没有形参,JavaScri ...
- JavaScript权威设计--JavaScript函数(简要学习笔记十)
1.函数命名规范 函数命名通常以动词为前缀的词组.通常第一个字符小写.当包含多个单词时,一种约定是将单词以下划线分割,就像"like_Zqz()". 还有一种就是"lik ...
- [Javascript] Array methods in depth - filter
Array filter creates a new array with all elements that pass the test implemented by the provided fu ...
- ArcGIS API for JavaScript 4.2学习笔记[1] 显示地图
ArcGIS API for JavaScript 4.2直接从官网的Sample中学习,API Reference也是从官网翻译理解过来,鉴于网上截稿前还没有人发布过4.2的学习笔记,我就试试吧. ...
随机推荐
- ios-系统警告框 跳转到设置里面
-(void)createUIAlertIphone:(NSString*)title { UIAlertController * alert =[UIAlertController alertCon ...
- mysql中profile的使用
1.profile在mysql5.0.37及其以上版本中可用 2.查看profile是否可用SELECT @@profiling;来查看是否已经启用profile,如果profilng值为0,可以通过 ...
- 【Android测试】【第十八节】Espresso——环境搭建
◆版权声明:本文出自胖喵~的博客,转载必须注明出处. 转载请注明出处:http://www.cnblogs.com/by-dream/p/5604642.html 前言 首先还是老规矩,看看官方文档吧 ...
- spring 连接各种数据源的配置(转载)
在 开发基于数据库的应用系统时,需要在项目中进行数据源的配置来为数据 库的操作取得数据库连接.配置不同数据库的数据源的方法大体上都是相同的,不同的只是不同数据库的JDBC驱动类和连接URL以及相应的数 ...
- (copy) DBAN vs nwipe
source: https://sourceforge.net/p/dban/discussion/208932/thread/cb591b59/ Question:Trouble in runnin ...
- javascript中的真假值、数据类型判断以及+的特殊用法
一.javascript中的假值 jQuery中拥有一组数量奇大的假值,包括 0,NaN(非数),''(空字符串),false,null,undefined 这些值在if判断中全部等于假,但这些值彼此 ...
- spring MVC配置详解
现在主流的Web MVC框架除了Struts这个主力 外,其次就是Spring MVC了,因此这也是作为一名程序员需要掌握的主流框架,框架选择多了,应对多变的需求和业务时,可实行的方案自然就多了.不过 ...
- 决策树Decision Tree 及实现
Decision Tree 及实现 标签: 决策树熵信息增益分类有监督 2014-03-17 12:12 15010人阅读 评论(41) 收藏 举报 分类: Data Mining(25) Pyt ...
- 配置MyBatis
创建WebProject之后先把mybatis-3.2.2.zip里的mybatis-3.2.2.jar包和lib里的asm-3.3.1.jar.cglib-2.2.2.jar.commons-log ...
- 监控web服务方法
本地监控:端口 netstat -anltup | grep 80 nmap ip -p 80 telnet ip:80 lsof -i :80|wc -l 进程 ps -ef| grep ngi ...