数组
标签(空格分隔): 排序sort
创建数组:
var arr=new Array(3,true,"gd","good");
var arr=["hello",33,55,true]
var arr = ["bob", "James", "Jet li", 45, "juli"];
console.log(arr.length);//5
console.log(arr.indexOf("Jet li"));//2
console.log(arr.slice(2,4));//取头不取尾 "Jet li", 45
console.log(arr.pop()); //juli
console.log(arr.length);//4
console.log(arr.push("Jack"));
console.log(arr);//["bob", "James", "Jet li", 45, "Jack"]
console.log(arr.unshift("angel",33));//从数组开始插入元素
console.log(arr); //"angel", 33, "bob", "James", "Jet li", 45, "Jack"
console.log(arr.shift())//弹出第一个元素
console.log(arr);//[33, "bob", "James", "Jet li", 45, "Jack"]
console.log(arr.splice(2,3,"red", "blue"));//返回删除的元素 ["James", "Jet li", 45]
console.log(arr);//[33, "bob", "red", "blue", "Jack"]
console.log(arr.join("|")); //33|bob|red|blue|Jack
console.log(arr.sort());//排序
console.log(arr.reverse());//反向排序
//concat 连接两个字符数组
console.log(arr.concat("hello","world"));//["red", "bob", "blue", "Jack", 33, "hello", "world"]
console.log(arr);//["red", "bob", "blue", "Jack", 33]
map函数
var arr = [2, 9, 3, 0, 2];
function f(x){
return x*x;
}
console.log(arr.map(f));//[4, 81, 9, 0, 4]
console.log(arr.map(String));//["2", "9", "3", "0", "2"]
reduce 函数
var arr = [2, 9, 3, 4, 2];//求和
function f(x,y){
return x+y;
}
console.log(arr.reduce(f));//20
var arr = [2, 9, 3, 4, 2];//求积
function f(x,y){
return x*y;
}
console.log(arr.reduce(f));//432
var arr = [2, 9, 3, 0, 2];输出29302
function f(x,y){
return x*10+y;
}
console.log(arr.reduce(f));//29302
排序 sort
默认排序是按照,字符串排序,ASCII码排序;
sort()方法会直接对Array进行修改,它返回的结果仍是当前Array
var arr = [2,4,99,33,9,20];
console.log(arr.sort());//[2, 20, 33, 4, 9, 99]
从大到小排序
var arr = [2,4,99,33,9,20];
function f(x,y) {
if(x<y){
return 1;
}
if{
return -1;
}
return 0;
}
console.log(arr.sort(f));//[99, 33, 20, 9, 4, 2]
从大到小排序
var arr = [2,4,99,33,9,20];
function f(x,y) {
if(x<y){
return -1;
}
if{
return 1;
}
return 0;
}
console.log(arr.sort(f));//[2, 4, 9, 20, 33, 99]