js 数组几种比较大小的方法
js 数组几种比较大小的方法。
·
one:正常的数组比较大小
var arr = [1,5,7,8,932,78,434];
function compareFN(arr) {//比较大小函数
var i = 0;
var j = 0;
let t;
for ( i = 0; i < arr.length; i++){
for (j = 0; j < arr.length; j++){
if (arr[i] < arr[j]){
t = arr[i];
arr[i] = arr[j];
arr[j] = t;
}
}
}
return arr
}
two:根据value字段排序数组大小
var arr2 = [
{value:1,name:'df'},
{value:4,name:'fd},
{value:2,name:'hgh},
{value:3,name:'uiu},
]
function compareFN(arr,property) {
var i = 0;
var j = 0;
let t;
for ( i = 0; i < arr.length; i++){
for (j = 0; j < arr.length; j++){
if (arr[i][property] < arr[j][property]){
t = arr[i];
arr[i] = arr[j];
arr[j] = t;
}
}
}
return arr
}
three:单纯两日期之间比较
function compareFN1(date1, date2) {//比较日期大小函数
let oDate1 = new Date(date1);
let oDate2 = new Date(date2);
if (oDate1.getTime() < oDate2.getTime()) {
return -1;
} else if (oDate1.getTime() > oDate2.getTime()) {
return 1;
} else {
return 0;
}
}
four:使用数组日期比较
var arr = ['2018-10-18','2018-10-1','2018-09-13','2019-03-14'];
function compareFN2(arr) {
var i = 0;
var j = 0;
let t;
for ( i = 0; i < arr.length; i++){
for (j = 0; j < arr.length; j++){
let oDate1 = new Date(arr[i]);
let oDate2 = new Date(arr[j]);
if (oDate1.getTime() < oDate2.getTime()){
t = arr[i];
arr[i] = arr[j];
arr[j] = t;
}
}
}
return arr
}
five:使用数组某个字段调用
var arr = [
{date:'2018-10-19',day:'晴朗'},
{date:'2017-12-16',day:'阴雨'},
{date:'2019-07-06',day:'大雨'},
{date:'2016-01-14',day:'大雪'},
]
function compareFN(arr,property) {
var i = 0;
var j = 0;
let t;
for ( i = 0; i < arr.length; i++){
for (j = 0; j < arr.length; j++){
let oDate1 = new Date(arr[i][property]);
let oDate2 = new Date(arr[j][property]);
if (oDate1.getTime() < oDate2.getTime()){
t = arr[i];
arr[i] = arr[j];
arr[j] = t;
}
}
}
return arr
}
six:数组中的对象排序
//反序
dataContent = ReverseRankingDate(dataContent, "received");
console.log(dataContent);
//封装的日期排序方法
function ReverseRankingDate(data, p) {
for (i = 0; i < data.length - 1; i++) {
for (j = 0; j < data.length - 1 - i; j++) {
console.log(Date.parse(data[j][p]));
if (Date.parse(data[j][p]) < Date.parse(data[j+1][p])) {
var temp = data[j];
data[j] = data[j + 1];
data[j + 1] = temp;
}
}
}
return data;
}
更多推荐
已为社区贡献7条内容
所有评论(0)