跳转到主要内容
模块 1 · 第 2 课(共 4)课程中的2/32~8 min
模块课程(2/4)

原始类型

JavaScript 中的每个值都有一个类型。原始类型是基本类型 语言的构建模块:它们不知从何而来,它们没有 它们自己的属性(即使有时它们看起来如此),并且您将使用 每天数百次。

JS
'ciao'; // string
42; // number
true; // boolean
null; // null
undefined; // undefined

您每天使用的五种类型

  • string — 文本。用单引号 '…'、双引号分隔 "…" or backticks `…` (template literals, which we'll see in the next module).
  • number — numbers. JS doesn't distinguish integers and decimals: 3 and 3.14 are both number.
  • boolean — truth or falsehood. Only allows true and false.
  • null — "no value", intentionally empty.你自己设置的 when you want to say "there is nothing here yet".
  • undefined — "no value", implicitly empty.这是默认的 value of variables declared but not initialized, and of function 未传递的参数。

使用 typeof 检查类型

The typeof operator returns a string describing the type of the 值:

JS
typeof 'ciao'; // 'string'
typeof 42; // 'number'
typeof true; // 'boolean'
typeof undefined; // 'undefined'
typeof null; // 'object'  ← rumore storico, non un vero "oggetto"

类型转换

通常,您会收到一个字符串(例如,来自 HTML 输入)并需要将其转换 成数字,反之亦然。显式转换是通过 函数 Number(...) 和 String(...):

JS
Number('42'); // 42
Number('3.14'); // 3.14
Number('ciao'); // NaN   ← Not-a-Number, "non rappresenta un numero"

String(42); // '42'
String(true); // 'true'

尝试一下

锻炼#js.m1.l2.e1
尝试:0加载中...

编写一个返回布尔值“typeof”的表达式。预期结果是字符串“boolean”。

正在加载编辑器...
显示提示

您可以将任何值或变量名称传递给 typeof。

3 次尝试后可用的解决方案

复习练习

锻炼#js.m1.l2.e2
尝试:0加载中...

将字符串“128”转换为数字并将其加倍。最后一个表达式的计算结果必须为 256。

正在加载编辑器...
显示提示

使用 Number(...) 进行显式转换,然后乘以 2。

3 次尝试后可用的解决方案