当前位置:网站首页>js的sort()函数
js的sort()函数
2022-06-25 04:00:00 【刘家奕_】
sort( )
-可以用来对数组中的元素进行排序
-也会影响原数组,默认会按照Unicode编码进行排序
即使对于纯数字的数组,使用sort()排序时,也会按照Unicode编码来排序,
所以对数字进排序时,可能会得到错误的结果。
我们可以自己来指定排序的规则
我们可以在sort()添加一个回调函数,来指定排序规则,回调函数中需要定义两个形参,
浏览器将会分别使用数组中的元素作为实参去调用回调函数使用哪个元素调用不确定,但是肯定的是在数组中a一定在b前边
-浏览器会根据回调函数的返回值来决定元素的顺序,
如果返回一个大于0的值,则元素会交换位置
如果返回一个小于0的值,则元素位置不变
如果返回一个日,则认为两个元素相等,也不交换位置
例如:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<script>
var arr = [2, 4, 6, 7];
arr.sort(function (a, b) {
//前边的大
if (a > b) {
return 1;
} else if (a < b) {
return -1;
} else {
return 0;
}
});
console.log(arr);
</script>
</body>
</html>

边栏推荐
- Smart contract learning materials
- GBASE 8s活锁、死锁问题的解决
- Laravel document sorting 10. Request life cycle
- Comparison of towe/ JIRA / tapd / Zen collaboration platforms
- CMD operation MySQL in Windows
- Lecture record: history and development of strapdown inertial navigation solution
- mysql的tinyint字段类型判断的疑惑
- 什么是持久化?redis 持久化中的RDB和AOF是什么?
- "Renaissance" in the digital age? The bottom digital collection makes people happy and sad
- GBASE 8s的隔离级别介绍
猜你喜欢

EasyRecovery15非常好用的电脑数据恢复软件

Lecture record: data processing methods and applications of various spatial geodetic techniques

Failed to install redis interface

Value transfer between parent and child components of wechat applet

CTF_ Web: deserialization of learning notes (II) CTF classic test questions from shallow to deep

Anaconda安装+TensorFlow安装+Keras安装+numpy安装(包含镜像和版本信息兼容问题)

Record small knowledge points

unity Quad剔除背面并剔除透明部分的shader

Nodejs connects to MySQL through heidisql, and ER appears_ BAD_ DB_ ERROR: Unknown database 'my_ db_ books'

Acmstreamopen return value problem
随机推荐
Easyrecovery15 very easy to use computer data recovery software
坐标系左乘右乘
微信小程序父子组件之间传值
EasyRecovery15非常好用的电脑数据恢复软件
GBASE 8s 总体架构
UCLA | 用于黑盒优化的生成式预训练
地方/園區產業規劃之 “ 如何進行產業定比特 ”
PHP extracts and analyzes table contents, and collects bidding information
Openmmlab environment configuration
Shutter fittedbox component
【LeetCode】143. Rearrange linked list
GBASE 8s的数据视图
GBASE 8s的多线程结构
English Grammar - pronunciation rules
Acmstreamopen return value problem
Lecture record: new application of inertial navigation - inertial measurement
GBASE 8s的并行操作问题场景描述
Text keyword extraction: ansj
navicat可不可以直接操作安卓数据库SQLite
i. Max development board learning record