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 经典实例:第三版
106
5
5.1
检查一个对象是不是数组
5.1.1
问题
在执行数组相关的操作之前,你想确认目标对象真的是数组。
5.1.2
方案
使用静态方法
Array.isArray()
const
browserNames = ['Firefox', 'Edge', 'Chrome', 'IE', 'Safari'];
if
(Array.isArray(browserNames)) {
//
代码执行到这里,因为
browserNames
是一个有效的数组
}
5.1.3
讨论
Array.isArray()
方法是显而易见的选择。不要使用过时的
instanceOf
运算符,你
会遇到一些问题。
instanceOf
运算符在处理数组时有一些怪异的边缘情况(例如,
测试在其他执行上下文,比如在另一个窗口中创建的数组,返回
false
),这是历
史遗留问题。为了弥补缺憾
isArray()
方法应运而出。
另外要注意,
isArray()
方法专门用于检查
Array
对象的实例。如果测试其他集合
类型(例如
Map
Set
),返回
false
。即使是语义上类似数组的集合,甚至名称
中有“数组”二字,例如类型化数组(
TypedArray
,对二进制数据缓冲区的底层包装),
isArray()
方法依然返回
false
5.2
迭代数组中的所有元素
5.2.1
问题
你想使用最好的方式按顺序遍历数组中的每一个元素。
数组
107
5.2.2
方案
传统的方法是使
for...of
循环,自动获取每一个元素。
const
animals = ['elephant', ...
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

JavaScript

T. J. Crowder
JavaScript

JavaScript

David Flanagan
JavaScript Patterns

JavaScript Patterns

Stoyan Stefanov

Publisher Resources

ISBN: 9787519869601