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 经典实例:第三版
50
2
这与本章开头的列表基本一致,不过有两处不同。第一,没有
null
,因为空值返回
字符串
object
(很多人认为这是一个
bug
,不过这是历史遗留问题)。第二,多了
一个
function
数据类型,不过从纯技术角度来看,函数是一种特殊的对象。
有时,你会见到下面这种过时的字符串验证技术。这里,变量不一定真是字符串,
验证的只是可以把值视作字符串,而且不为空字符串。
if
(unknownVariable) {
/*
满足以下条件:
unknownVariable
已经声明
unknownVariable
不是
null
unknownVariable
不是空字符串
''
*/
}
之所以可以这样检查,是因为在
JavaScript
中,
null
值、
undefined
值和空字符串(
''
都是假值。在条件表达式中,这些值的求值结果都是
false
这种方法在测试数字
0
时不起作用,因为
0
的求值结果始终
false
,从而跳过
if
块。安全起见,最好把数值变量显式转换为字符串,详见
2.2
节。
2.2
把数值转换为格式化字符串
2.2.1
问题
你想创建数字的字符串表示形式。
2.2.2
方案
JavaScript
是弱类型语言,在必要时会把任何值自动转换成字符串,例如比较一个
数字和一个字符串时,或者使用
+
运算符拼接一个数字和一个字符串时。其实,
JavaScript
开发者经常使用一个小技巧把数字转换成字符串:在值的开头或结尾拼接
一个空字符串。
const
someNumber
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