定义数组的方式
(javascript数组不越界,越界会返回undefined)
var arr = [];
var arr = new Array();
var arr = new Array(10);
var arr1 = [10];
数组常用方法
1.push,pop,shift,unshift,reverse(改变原数组)
var arr = [1,2];
Array.prototype.push = function(){
for(var i = 0;i<arguments.length;i ++)
{
this[this.length] = arguments[i];
}
arr[arr.length];
return this.length;
}
2.sort(改变原数组)
var arr = [1,2,3,4,5,6,7,8,9,10];
arr.sort(function (a,b) {
return b - a;
});
3.join,concat,split,toString,slice
arr = [1,2,3,4,5];
arr1 = [7,8,9];
var newArray = arr.slice(1,3);
eg.arr.join("-")
arr.split('-')
数组方法的应用
1.对象按年龄排序
var cheng = {
name : 'cheng',
age : 18,
sex : 'male'
}
var deng = {
name : 'deng',
age : 40,
sex : 'male'
}
var zhang = {
name : 'zhang',
age : 20,
sex : 'male'
}
var arr = [zhang,deng,cheng];
arr.sort(function(a,b){
return a.age - b.age;
});
2.按字符串长度排序
var arr = ['ac', 'weer', 'sfd', 'adfhg', 'q', 'seraffggd', 'safaef'];
arr.sort(function (a, b) {
return a.length -b.length;
});
3.根据字节长度排序
function retBytes(str) {
var count = str.length;
for (var i = 0; i < str.length; i++) {
if (str.charCodeAt(i) > 255) {
count++;
}
}
return count;
}
var arr = ['ac邓', 'weer', 'sfd老邓', 'adfhg', 'q', 'seraffggd', 'safaef'];
arr.sort(function (a, b) {
return retBytes(a) - retBytes(b);
return retBytes(b) - retBytes(a);
});
4.join的应用(连接字符串)
var str = 'alibabb';
var str1 = 'baidu';
var str2 = 'tencent';
var str3 = 'toutiao';
var str4 = 'wangyi';
var str5 = 'xiaomi';
var str6 = 'nv';
var arr = [str,str1,str2,str3,str4,str5,str6];
console.log(arr.join("")
类数组
var obj = {
'2' : 'a',
'3' : 'b',
'4' : 'c',
'length' : 3,
'push' : Array.prototype.push,
'splice' : Array.prototype.splice
}
Array.prototype.push = function(target){
this[this.length] = target;
this.length ++;
}
|