Javascript语言精粹之Array常用方法分析
Javascript语言精粹之Array常用方法分析
1、Array常用方法分析
1.1 Array.prototype.sort()
Javascript的默认比较函数假定被排序元素都是字符串,所以直接调用sort方法,不能正确对数字数组排序
var n=[3,11,6,23];
n.sort();
alert(n);//n: 11,23,3,6
我们可以使用自己的比较函数来进行排序,如果想要给任何简单值类型数组排序(知识点,Javascript基本数据类型不多,有string,number,boolean,undefined,null)
var m=['aa',4,'b',12,2];
m.sort(function(a,b){
if(a===b){
return 0;
}
if(typeof a === typeof b){ return a<b ? -1 : 1;
}
return typeof a < typeof b ? -1 : 1; });
alert(m);// 2,4,12,aa,b
如果需要以对象数组的某一熟悉为关键字进行排序
var by=function(name){
return function(o,p){
var a,b;
if(o && p && typeof o === 'object' && typeof p ==='object'){
a=o[name];
b=p[name];
if(a===b){
return 0;
}
if(typeof a === typeof b){
return a<b ? -1 : 1;
}
return typeof a < typeof b ? -1: 1;
}else{
throw{
name:'error',
message:'expected an object when sorting by '+name
}
} }
}; var s=[
{first:'moe',last:'besser'},
{first:'joe',last:'haha'},
{first:'joe',last:'abc'}
]; s.sort(by('first')); s=[
{first:'joe',last:'haha'},
{first:'joe',last:'abc'},
{first:'moe',last:'besser'}
];
上述排序,发现仅按单个key排序时,
{first:'joe',last:'haha'}排在了{first:'joe',last:'abc'}
如果需要last为abc的对象排在前面,就需要基于多个key进行排序,此时可让by第二个参数为一个比较函数
var by=function(name,minor){
return function(o,p){
var a,b;
if(o && p && typeof o === 'object' && typeof p ==='object'){
a=o[name];
b=p[name];
if(a===b){
return typeof minor === 'function' ? minor (o,p) : 0;
}
if(typeof a === typeof b){
return a<b ? -1 : 1;
}
return typeof a < typeof b ? -1: 1;
}else{
throw{
name:'error',
message:'expected an object when sorting by '+name
}
} }
}; var s=[
{first:'moe',last:'besser'},
{first:'joe',last:'haha'},
{first:'joe',last:'abc'}
]; s.sort(by('first',by('last'))); s=[
{first:'joe',last:'abc'},
{first:'joe',last:'haha'},
{first:'moe',last:'besser'}
];
};
1.2 Array.prototype.splice()
array.splice(start,deleteCount,item...)方法从array中移除一个或多个元素,并用新的item替换他们。start是移除元素的开始位置,deleteCount是要移除的元素个数,如有额外插入的参数,这些item将被插入到所移除元素的位置上。返回一个包含被移除元素的数组。
var a=['a','b','c'];
var r=a.splice(1,1,'ache','bug');
//a是['a','ache','bug','c']
//r是['b']
splice实现代码和详细解读
Array.prototype.splice=function(start,deleteCount){
var max=Math.max,
min=Math.min,
delta,//偏移量
element,
insertCount=max(arguments.length-2,0),//排除掉arguments参数中,start,deleteCount,剩余是待插入元素
k=0,
len=this.length,//对array调用时,this指向当前数组
new_len,
result=[],//返回数组
shift_count//需移位的数量; start = start || 0;//start默认值为0
if(start<0) start+=len;//start<0时,从数组后端开始
start=max(min(start,len),0);//经过处理,0<=start<=len
deleteCount=typeof deleteCount === 'number' ? deleteCount : len;//deleteCount默认值是len
deleteCount=min(deleteCount,len-start);//deleteCount<=可删除数量
deleteCount=max(deleteCount,0);//0<=deleteCount<=可删除数量 delta=insertCount-deleteCount;
new_len=len+delta; //获取删除元素
while(k<deleteCount){
element=this[start+k];
if(element!=undefined){
result[k]=element;
}
k +=1;
}
shift_count=len-start-deleteCount;
//待插入数量小于删除数量,原数组后续元素依次向左偏移
if(delta<0){
k=start+insertCount;//从start至start+insertCount留给待插入元素
while(shift_count){
this[k]=this[k-delta];
k+=1;
shift_count-=1;
}
this.length=new_len;
}
//待插入数量大于删除数量,原数组后续元素依次向右偏移
else if(delta>0){
k=1;
while(shift_count){
this[new_len-k]=this[len-k];
k+1;
shift_count-=1;
}
//this.length=new_len;非必须,因给一开始this[new_len-k]赋值时,length属性已经自动设置为数组最后元素下标值
}
//delta===0 时,待插入数量等于删除数量,无需偏移 //最后将待插入元素插入原数组
for(k=0;k<insertCount;k+=1){
this[start+k]=arguments[k+2];//排除掉arguments参数中start和deleteCount
}
return result;
});
1.3 Array.prototype.slice()
array.slice(start,end)方法是对array中一部分做浅复制,end参数可选,默认为array.length
注意,slice方法不改变原数组,返回新的结果数组
var a=['a','b','c'];
var b=a.slice(0,1);//b是['a']
var c=a.slice(1);//c是['b','c']
alert(a);//['a','b','c']
1.4 Array.prototype.push()、Array.prototype.pop()
push、pop方法可以实现栈的先进后出。
push(item...)方法将一个或多个参数item附加到一个数组的尾部,返回数组新的长度值
var a=['a','b','c'];
var b=[1,2];
var c=a.push(b,true);
//a=['a','b','c',[1,2],true];
//c=5
push方法实现和详细解读
Array.prototype.push=function(){
//对arguments对象通过array.slice方法转换成数组
var args=Array.prototype.slice.apply(arguments);
//通过array.concat,连接两个数组
var params=[this.length,0].concat(args);
//对数组调用splice方法,start=this.length,deleteCount=0,insertItems=args
this.splice.apply(this,params);
//返回新的数组length
return this.length;
});
//上述步骤合并,简写为下面方式
Array.prototype.push=function(){
this.splice.apply(
this,
[this.length,0].concat(Array.prototype.slice.apply(arguments)));
return this.length;
});
pop方法移除array最后的一个元素并返回该元素,array为空时,返回undefined
var a= ['a','b','c'];
var c = a.pop();
//a是['a','b'],c是'c' Array.prototype.pop=function(){
//start=this.length-1,deleteCount=1,结果数组的第[0]个元素
return this.splice(this.length-1,1)[0];
}
1.5 Array.prototype.shift()、Array.prototype.unshift()
array.shift()方法移除数组array中第一个元素并返回该元素。数组为空时,返回undefined
var a= ['a','b','c'];
var c = a.pop();
//a是['b','c'],c是'a'
shift可以这样实现
Array.prototype.shift=function(){
//start=0,deletecount=1,返回结果数组中第[0]个元素
return this.splice(0,1)[0];
}
unshift将item插入array的开始部分
var a = ['a','b','c'];
var r=a.unshift('?','@');
//a是['?','@','a','b','c'];
//r是5
unshift可以像这样实现
Array.prototype.unshift=function(){
//start=0,deleteCount=0,insertItems=arguments
this.splice.apply(this,
[0,0].concat(Array.prototype.slice.apply(arguments)));
return this.length;
});
Javascript语言精粹之Array常用方法分析的更多相关文章
- Javascript语言精粹之String常用方法分析
Javascript语言精粹之String常用方法分析 1. String常用方法分析 1.1 String.prototype.slice() slice(start,end)方法复制string的 ...
- 《JavaScript语言精粹》小记
一.前言 以下内容均摘自<JavaScript语言精粹>一书,本人在读这本书时,发现作者诠释JavaScript很犀利,特别是数组部分,固记录下来,想和大家分享下. 随笔主要包含两大部分: ...
- javascript语言精粹
内容选自:<javascript语言精粹> 1.6种值会为假(==false),分别是false,null,undefined,' ',0,NaN 2.typeof有6种值,分别是'num ...
- Javascript 语言精粹 代码片段合集
Javascript 语言精粹 代码片段合集 标签:Douglas-Crockford Javascript 最佳实践 原文链接 更好的阅读体验 使用一个method 方法定义新方法 Function ...
- 《JavaScript语言精粹》学习笔记
一.in的用法 for...in 枚举一个对象的所有可枚举属性 检测DOM/BOM属性 if ("onclick" in elem) { // 元素支持onclick } if ( ...
- 《JavaScript语言精粹》【PDF】下载
<JavaScript语言精粹>[PDF]下载链接: https://u253469.pipipan.com/fs/253469-230382204 内容简介 javascript曾是&q ...
- JavaScript语言精粹 笔记06 方法
JS包含了少量可用在标准类型上的标准方法. ArrayFunctionNumberObjectRegExpString Array array.concat(item...) concat方法返回一个 ...
- JavaScript语言精粹 笔记04 数组
数组1 数组字面量2 长度3 删除4 列举5 混淆的地方6 方法7 维度 数组1 数组字面量 var empty = []; var numbers = [ 'zero', 'one', 'two', ...
- JavaScript语言精粹 笔记03 继承
继承伪类对象说明符原型函数化部件 继承 JS不是基于类的,而是基于原型的,这意味着对象直接从其他对象继承. 1 伪类 JS提供了一套丰富的代码重用模式,它可以模拟那些基于类的模式,因为JS实际上没有类 ...
随机推荐
- Type Unknown error: java.lang.NullPointerException
Android 项目开发的时候 出现: Description Resource Path Location Type Unknown error: java.lang.NullPointerExce ...
- Delphi的字符(Char),字符串(String),字符串指针(PChar),字符数组arrayofchar(来自http://delphi.cjcsoft.net/论坛)
Delphi有三种类型的字符: AnsiChar这是标准的1字节的ANSI字符,程序员都对它比较熟悉. WideChar这是2字节的Unicode字符. Char在目前相当于AnsiChar,但在De ...
- java中synchronized的使用方法与具体解释
Java语言的keyword.当它用来修饰一个方法或者一个代码块的时候,可以保证在同一时刻最多仅仅有一个线程运行该段代码. 一.当两个并发线程訪问同一个对象object中的这个synchronized ...
- ASP.Net状态管理读书笔记--思维导图
课前提问几个问题 使用Session 配置 model aspnet_regsql.exe 常见问答 问:为什么Session在有些机器上偶尔会丢失?答:可能和机器的环境有关系,比如:防火墙或者杀毒软 ...
- android studio下的NDK开发详解(一)
源地址:http://www.voidcn.com/blog/chengkaizone/article/p-5761016.html 好记性不如烂笔头,开始坚持写博客,学一点记一点,只为了生活更好. ...
- 使用Delphi声明C++带函数的结构体实战 good
在小组开发中,应用程序部分采用Delphi7,一些组件使用C++做.在今天将一个动态库的C++接口声明头文件转换为D7的Unit单元时,一切都很顺利,直到遇到下面这样一个另类的东西: typedef ...
- 更好的自动ssh登录
更好的自动ssh登录 解决~/.ssh/known_hosts 过期问题. bash + expect bash:ssh.sh #!/bin/bash help(){ echo "usage ...
- iOS学习——iOS国际化(十二)
开发的移动应用更希望获取更多用户,走向世界,这就需要应用国际化,国际化其实就是多语言.这篇文章介绍Xcode4.5以后的国际化,包括应用名国际化和应用内容国际化.如果是Xcode4.5之前版本请参考. ...
- HDU 4611 Balls Rearrangement (数学-思维逻辑题)
题目地址:http://acm.hdu.edu.cn/showproblem.php?pid=4611 题意:给你一个N.A.B,要你求 AC代码: #include <iostream> ...
- [Python]网络爬虫(十):一个爬虫的诞生全过程(以山东大学绩点运算为例)
先来说一下我们学校的网站: http://jwxt.sdu.edu.cn:7777/zhxt_bks/zhxt_bks.html 查询成绩需要登录,然后显示各学科成绩,但是只显示成绩而没有绩点,也就是 ...