Skip to Content
JavaScript 经典实例:第三版
book

JavaScript 经典实例:第三版

by Adam D. Scott, Matthew MacDonald, Shelley Powers
September 2022
Intermediate to advanced
585 pages
8h 17m
Chinese
China Electric Power Press Ltd.
Content preview from JavaScript 经典实例:第三版
130
5
const
animals = ['cat', 'walrus', 'lion', 'cat'];
//
删除一个元素,添加两个新元素
animals.splice(2, 1, 'zebra', 'elephant');
//
现在
animals = ['cat', 'walrus', 'zebra', 'elephant', 'cat']
你可以在循环中使
indexOf()
方法查找并删除一系列匹配元素。不过,实现相同
的操作,使用
filter()
方法往往更简洁,定义一个函数挑出想保留的元素即可(见
5.9
节)。
5.16
按属性值排序对象数组
5.16.1
问题
你想根据属性值排序包含对象的数组。
5.16.2
方案
Array.sort()
法重新排列数组中元素的顺序。例如,按照从小到大的顺序排列数
组中的数字元素,或者按照字母表顺序排列数组中的字符串元素。但是,你并不总
是想使用标准的数组排序系统。你可以把一个比较函数传给
sort()
法,通过这个
函数排列元素的顺序。
传入的比较函数接收两个参数(对应两个数组元素),经比较之后返回一个数字,
表示比较结果。如果两个值相等,返回
0
;如果第一个值比第二个值小,返回
-1
如果第一个值比第二个值大,返回
1
下面举个简单的例子,对包含人物信息对象的数组进行排序。
const
people = [
{ firstName: 'Joe', lastName: 'Khan', age: 21 },
{ firstName: 'Dorian',
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.

Read now

Unlock full access

More than 5,000 organizations count on O’Reilly

AirBnbBlueOriginElectronic ArtsHomeDepotNasdaqRakutenTata Consultancy Services

QuotationMarkO’Reilly covers everything we've got, with content to help us build a world-class technology community, upgrade the capabilities and competencies of our teams, and improve overall team performance as well as their engagement.
Julian F.
Head of Cybersecurity
QuotationMarkI wanted to learn C and C++, but it didn't click for me until I picked up an O'Reilly book. When I went on the O’Reilly platform, I was astonished to find all the books there, plus live events and sandboxes so you could play around with the technology.
Addison B.
Field Engineer
QuotationMarkI’ve been on the O’Reilly platform for more than eight years. I use a couple of learning platforms, but I'm on O'Reilly more than anybody else. When you're there, you start learning. I'm never disappointed.
Amir M.
Data Platform Tech Lead
QuotationMarkI'm always learning. So when I got on to O'Reilly, I was like a kid in a candy store. There are playlists. There are answers. There's on-demand training. It's worth its weight in gold, in terms of what it allows me to do.
Mark W.
Embedded Software Engineer

You might also like

JavaScript Patterns

JavaScript Patterns

Stoyan Stefanov
JavaScript

JavaScript

David Flanagan
JavaScript

JavaScript

T. J. Crowder

Publisher Resources

ISBN: 9787519869601