JavaScript基础之sort()方法

一、sort()方法:

  1. 调用每个数组项的toString()方法
  2. 比较字符串,按升序排列数组
var items = ["d", "a", "b", "e", "c"];
items.sort();
alert(items);

alert()会先调用数组的toString方法然后显示

二、数组的值是number的情况下调用sort()方法

sort()不会按照数值大小升序排列而是按字符串大小排列

var items = [8, 10, 3, 11, 2, 1];
items.sort();
alert(items);


三、如何按数值大小排序?

答案:sort()方法可以接受一个参数,该参数只能是函数,我们成这个函数为比较函数

比较函数需要至少接受2个参数指定排序规则,其返回值如下:

    若 a 小于 b,在排序后的数组中 a 应该出现在 b 之前,则返回一个小于 0 的值。

    若 a 等于 b,则返回 0。

    若 a 小于 b,在排序后的数组中 a 应该出现在 b 之前,则返回一个小于 0 的值。

var items = [8, 10, 3, 11, 2, 1];

function compare(num1, num2) {
if (num1 > num2) {
return 1;
} else if (num1 == num2) {
return 0;
} else {
return -1
};
}

items.sort(compare);
alert(items);


四、改进(三、)中的比较函数

var items = [8, 10, 3, 11, 2, 1];

function compare(num1, num2) {
return num1 - num2;
}

items.sort(compare);
alert(items);

五、依据对象的属性1的顺序,排列对象的属性2

var person1 = {
name: "姚明",
age: 38,
height: 224,
toString: function() {
return this.name;
}
};
var person2 = {
name: "郭敬明",
age: 27,
height: 140,
toString: function() {
return this.name;
}
};
var person3 = {
name: "老刘",
age: 40,
height: 175,
toString: function() {
return this.name;
}
}

persons = [person1, person2, person3];

function compare(property) {
return function(a, b) {
aProperty = a[property];
bProperty = b[property];
return aProperty - bProperty;
}
}

persons.sort(compare("height"));
alert(persons);


六、在(五、)的基础上,实现选择升序降序功能

var person1 = {
name: "姚明",
age: 38,
height: 224,
toString: function() {
return this.name;
}
};
var person2 = {
name: "郭敬明",
age: 27,
height: 140,
toString: function() {
return this.name;
}
};
var person3 = {
name: "老刘",
age: 40,
height: 175,
toString: function() {
return this.name;
}
}

persons = [person1, person2, person3];

function compare(property, rev) {
if (rev == undefined) {
rev = 1;
} else {
rev = (rev) ? 1 : -1;
}
return function(a, b) {
aProperty = a[property];
bProperty = b[property];
return rev * (aProperty - bProperty);
}
}

persons.sort(compare("height", false));
alert(persons);


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值