跳轉到內容

JavaScript/原始資料型別

來自華夏公益教科書



原始型別使用固定格式;有些只能包含有限數量的特定值。相反,物件更復雜,尤其包括方法和屬性。

除了 nullundefined,原始型別都有相應的 物件包裝器,包含特定於資料型別的方法。因此,您將在本頁上找到一些方法的描述。

字串 是一種資料型別,用於儲存任意長度的文字。字串變數透過將字串字面量賦給它們來建立。字串字面量可以包含在 " "' ' 中。

"use strict";
const myName_1 = "Mike";      // double quote
const myName_2 = 'Monica';    // apostrophe
const myName_3 = "naɺ̠ɯçito";  // non-latin characters

如果您的字串字面量包含 "',您可以使用另一個作為外部分隔符,或者使用 \ 對它們進行轉義。

"use strict";
const book_1 = "Mike's book";
const monica_1 = 'Here name is "Monica".';
const book_2 = 'Mike\'s book';
const monica_2 = "Here name is \"Monica\".";

如果您的字串字面量是由一些固定文字加上一些動態部分計算出來的,您可以使用 模板字面量 技術。這裡,字面量包含在反引號 ` ` 中,幷包含變數和表示式。

"use strict";
const a = 1;
const b = 2;
const resultMessage = `The sum of ${a} and ${b} is: ${a + b}.`;
// same as:
         'The sum of ' + a + ' and ' + b + ' is: ' + (a + b);
alert(resultMessage);

+ 運算子連線兩個字串,例如 alert("Hello " + "world!");。此外,還有很多用於字串的 方法

提示:JavaScript 沒有類似 '字元' 或 '位元組' 資料型別的東西。

字串的屬性和方法

[編輯 | 編輯原始碼]

我們展示了一些常用的方法。有關完整列表,請參閱 MDN

length 是一個屬性,而不是一個方法。因此沒有括號 ()。它返回字串的長度,作為一個整數。

const foo = "Hello!";
alert(foo.length);    // 6

includes(searchText)

[編輯 | 編輯原始碼]

如果字串包含指定的字串,則該方法返回 true,否則返回 false

let text = "Hello world, hello Wikiversity!";
document.write(text.includes("Hello")); //true

concat(text)

[編輯 | 編輯原始碼]

該方法返回一個字串,其中 'text' 附加到原始字串。

const foo = "Hello";
const bar = foo.concat(" World!");
alert(bar);	// Hello World!

indexOf(searchText)

[編輯 | 編輯原始碼]

該方法返回 'searchText' 首次出現的索引,從 0 開始。如果找不到 'searchText',則返回 -1。該方法區分大小寫。

const foo = "Hello, World! How do you do?";
alert(foo.indexOf(" "));	// 6

const hello = "Hello world, welcome to the universe.";
alert(hello.indexOf("welcome"));      // 13

search(regularExpression)

[編輯 | 編輯原始碼]

該方法將字串與正則表示式(=模式)進行比較,返回字串中第一個匹配項的索引。它類似於 indexOf(),但功能更強大。例如:它可以透過用正斜槓替換 "hello" 中的引號以及結尾的 i 來忽略大小寫。

let text = "Hello world, hello Wikiversity!";
document.write(text.search(/hello/i)); // 0

lastIndexOf(searchText)

[編輯 | 編輯原始碼]

該方法返回 'searchText' 最後一次出現的索引。如果找不到 'searchText',則返回 -1。該方法區分大小寫。

const foo = "Hello, World! How do you do?";
alert(foo.lastIndexOf(' '));	// 24

replace(text, newtext)

[編輯 | 編輯原始碼]

該方法返回一個字串,其中 'text' 在原始字串中被 'NewText' 替換。僅替換第一次出現的文字。該方法區分大小寫。

const foo = "foo bar foo bar foo";
const newString = foo.replace("bar", "NEW"):
alert(foo);		    // foo bar foo bar foo
alert(newString);	// foo NEW foo bar foo

如您所見,replace 方法只返回新內容,而不會修改 'foo' 中的原始字串。

slice(start [, end])

[編輯 | 編輯原始碼]

該方法返回從 'start' 位置開始的子字串。

"hello".slice(1);	// "ello"

當提供 'end' 時,它們將提取到,但不包括結束位置。

"hello".slice(1, 3);	// "el"

slice 允許透過使用負索引來提取從字串末尾引用的文字。

"hello".slice(-4, -2);	// "el"

substring 不同,slice 方法永遠不會交換 'start' 和 'end' 位置。如果 'start' 在 'end' 之後,slice 將嘗試按照給定方式提取內容,但很可能會產生意外的結果。

"hello".slice(3, 1);	// ""

substr(start [, 字元數])

[編輯 | 編輯原始碼]

該方法已 棄用。請改用 substringslice

substring(start [, end])

[編輯 | 編輯原始碼]

該方法從 'start' 位置開始提取子字串。

"hello".substring(1);	// "ello"

當提供 'end' 時,它們將提取到,但不包括結束位置。

"hello".substring(1, 3);	// "el"

substring 始終從左到右工作。如果 'start' 位置大於 'end' 位置,substring 將交換這些值;儘管有時有用,但這並不總是您想要的;slice 提供不同的行為。

"hello".substring(3, 1);	// "el"

toLowerCase()

[編輯 | 編輯原始碼]

該方法以小寫形式返回當前字串。

const foo = "Hello!";
alert(foo.toLowerCase());	// hello!

toUpperCase()

[編輯 | 編輯原始碼]

該方法返回當前字串的大寫形式。

const foo = "Hello!";
alert(foo.toUpperCase());	// HELLO!

數字 是兩種數值型別之一(另一種是 BigInt)。數字IEEE 754 定義的統一 64 位格式儲存整數和浮點數。這意味著,JavaScript 並沒有像其他一些語言那樣為整數和浮點數使用不同的資料型別。

此類值的可能範圍近似為 -10300 到 +10300,精度因距離 0 的遠近而異。

在 -(253 − 1) 到 +253 − 1 的範圍內,整數運算沒有不確定性。253 = 9,007,199,254,740,992,略小於 1016

"use strict";
let counter = 20;   // no decimal point
alert(counter + " " + typeof counter);
let degree = 12.1;  // with decimal point
alert(degree + " " + typeof degree);

對於 數字,常用的算術運算子('冪' 為 **,'模' 為 %)、比較運算子(<> 等)和位運算子都可用。

與其他一些語言不同,兩個整數的除法可能導致帶有小數部分的數字,例如 alert(1/3);

數字的屬性和方法

[編輯 | 編輯原始碼]

許多屬性和方法支援數字運算。在內部,它們在不同的區域實現

  • 內建物件 Math 提供表示常用數學常量(如 πe)的屬性。語法:Math.xyz(無括號)
  • 內建物件 Math 提供常用的數學函式(如 sinlog)。語法:Math.xyz()(帶括號)
  • 物件 Number 提供表徵數字資料型別實現的屬性,如 MAX_VALUENEGATIVE_INFINITY。語法:Number.xyz(無括號)
  • 物件 Number 提供檢查數字與其他資料型別之間關係的 靜態 方法,例如 isIntegerparseFloat。語法:Number.xyz()(帶括號)
  • 物件 Number 提供作用於具體數字值或變數的 例項 方法,例如 toExponentialtoFixed。語法:value.xyz()(帶括號)
// some examples
"use strict";

const var_1 = Math.PI;
alert(var_1);
alert(var_1.toFixed(2));

const var_2 = Math.sqrt(3);
alert(var_2);

alert(Number.MAX_VALUE);

alert(Number.isInteger(123));    // true
alert(Number.isInteger(12.3));   // false

我們展示了一些常用的屬性和方法。有關完整列表,請參閱 MDN MathMDN Numbers

最常用的常量

  • Math.E 返回常數 e。
  • Math.PI 返回常數 pi。
  • Math.LN10 返回 10 的自然對數。
  • Math.LN2 返回 2 的自然對數。
  • Math.SQRT2 返回 2 的平方根。

Math.ceil(number)

[編輯 | 編輯原始碼]

返回作為引數傳遞的數字的最小的整數

const myInt = Math.ceil(90.8);
alert(myInt);              //  91
alert(Math.ceil(-90.8));   // -90

Math.floor(number)

[編輯 | 編輯原始碼]

返回作為引數傳遞的數字的最大的整數

const myInt = Math.floor(90.8);
alert(myInt);              //  90
alert(Math.floor(-90.8));  // -91

Math.round(number)

[編輯 | 編輯原始碼]

返回作為引數傳遞的數字的最接近的整數

alert(Math.round( 90.8));  //  91
alert(Math.round(-90.8));  // -91

alert(Math.round( 90.3));  //  90
alert(Math.round(-90.3));  // -90

Math.max(number_1, number_2)

[編輯 | 編輯原始碼]

返回作為引數傳遞的兩個數字中較大的數字。

alert(Math.max(8.3,  9));  //  9
alert(Math.max(8.3, -9));  //  8.3

Math.min(number_1, number_2)

[編輯 | 編輯原始碼]

返回作為引數傳遞的兩個數字中較小的數字。

alert(Math.min(8.3,  9));   //  8.3
alert(Math.min(8.3, -9));   // -9

Math.random()

[編輯 | 編輯原始碼]

生成 0 到 1 之間的偽隨機數。

alert(Math.random());

Number.parseInt(string)

[編輯 | 編輯原始碼]

Number.parseFloat(string)

[編輯 | 編輯原始碼]

parseIntparseFloat 這兩種方法將字串轉換為數字。它們從左到右掃描給定的字串。當它們識別到一個與 0 - 9 不同的字元時,它們會停止掃描並返回迄今為止讀取的轉換後的數字(parseFloat 接受小數點)。如果第一個字元與 0 - 9 不同,則返回 Math.NaN,表示 不是數字

提示:在原始碼中不需要指定 'Number.'。

const x = parseInt("7.5");
alert(x);  // 7

const y = parseInt("Five");
alert(y);  // NaN

const z = parseFloat("2.8") + 3;
alert(z);  // 5.8

// scientific notation is accepted
alert(parseFloat("123.456e6"));  // 123456000

BigInt 是一個數據型別,表示任意長度整數。因此,它是一種可變長度格式(概念上),僅受可用 RAM 的限制。

BigInt 的建立方法是在整數字面量末尾新增 'n',或者使用 BigInt() 函式。

"use strict";
let hugeNumber_1 = 12345678901234567890n;        // 'n' at the end
alert(typeof hugeNumber_1);
let hugeNumber_2 = BigInt("12345678901234567890"); // no 'n'
alert(typeof hugeNumber_2);
// a 'small' BigInt can be created out of an integer value
let hugeNumber_3 = BigInt(123);
alert(typeof hugeNumber_3);

BigInt 支援算術運算子 + - * / **、比較運算子和大多數位運算子。

布林值

[編輯 | 編輯原始碼]

布林變數可以包含兩個可能的值之一,truefalse。JavaScript 透過布林值 false、數字 0、NaN、空字串或內建型別 undefined 或 null 來表示 false。任何其他值都將被視為 true

"use strict";
let firstLoop = true;
alert(typeof firstLoop);

未定義

[編輯 | 編輯原始碼]

那些只是宣告但沒有初始化任何值的變數具有 undefined 資料型別。

"use strict";
let x;
// ...
alert(typeof x);
if (x == undefined) {
  // remedy the missing initialization
  x = 0; 
}
alert(typeof x);
// ...

在 JavaScript 中,null 被標記為基本值之一,因為它的行為看似是基本的。但是,當使用 typeof 運算子時,它返回 "object"。這被認為是一個錯誤,但無法修復,因為它會破壞過多的指令碼。[1]

Symbol 代表一個唯一的識別符號。Symbol 可以有一個描述符,以字串的形式傳遞給其建構函式。

"use strict";
// 'person' is a symbol with the description "Olaf"
const person = Symbol("Olaf");
alert(person.description); // Olaf

Symbols 用作物件中的鍵(嵌入在 [ ] 中)以保證唯一性。

另請參閱

[編輯 | 編輯原始碼]

ECMAScript 關於資料型別的定義

... 在另一個頁面上(點選這裡)。

參考文獻

[編輯 | 編輯原始碼]
  1. MDN: Null
華夏公益教科書