JS数组
数组
var arr =[,,3,3,] //稀松数组
var arr = new Array(); 不支持上述传值;
var arr = Array();
-
push : 后面加入值 push(1,2....);可以为多个,,返回值是 执行完操作的长度;
-
unshift unshift(1,2....);可以为多个,, 返回值是 执行完操作的长度;
-
push 的重写
Array.prototype.myPush = function(){
for(var i = 0; i < arguments.length;i++){
this.arguments[this.length] = arguments[i];
}
return this.length;
}
或者用 contact 方法进行连接
- unshift 的重写
Array.prototype.myUnshift = function(){
var position = 0;
for(var i = 0; i < arguments.length;i++){
this.splice(position,0,arguments[i]);
position++;
}
return this.length;
}
或者用 contact 方法进行连接
修改原数组
-
pop 删除最后一位,并返回
-
shift 删除第一位,并返回
-
reverse 倒序数组
-
splice: 删除数组中任意位,并且在删除的下标添加新元素 返回值为
-
startIndex 开始下表
-
剪切长度
-
剪切后最后一位开始添加数据
-
例如 var arr = [a,b,c]; arr.splice(1,1,bvvv,cc)'; arr = [a,bvvvv,cc,c];
-
splice 可以重写新unshift(),方法 例如:splice(0,0,3,3,4);
- splice 可以传负数;底层下标的确定
index += index >= 0 ? 0 : arr.length;
如果大于零,不变;复制时,index + length;
-
sort : 按照Ascii码来排列; 就和字符串比较值一样;'7' > '66'
-
如果第一位的Ascii码大于其他的,后面的就不看了,
-
可以传入回调:原理就是冒泡排序
-
规则: 1,参数a,b
2,返回值:负值; a在b前; 正值:b 在a前; 0 不变
sort(function(a,b){
return a - b; 从小到大
return b - a; 从大到小
});
扩展:随机排序
sort(function(a,b){
return Math.random() -0.5; 从小到大
});
返回新数组
-
contact 连接数组;var a= [1,2]; a.contact([2,3,45]); 返回值名为截取的数组
-
slice 复制数组;可以填负值
-
[startIndex ,开始下标,并包含
-
endIndex),结束下标,不包含
-
-
join : 将数组用特定符号相连
-
split:用特定符号分割,变成数组
-
分隔符;
-
长度;
-
例如;var c = "a,b,c"; var arr = c.split(',',2); arr = [a,b];
-
类数组;
- 类数组转换换为数组
Array.prototype.slice.call(arguments);
var obj = {
2:3,
3:4,
splice:Array.prototype.splice, //有了splice方法就能显示为数组形式
push:Array.prototype.push,
length:2
}