跳轉到內容

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' 時,將提取到但不包括 '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' 時,將提取到但不包括 '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)。數字以統一的 64 位格式儲存整數值和浮點值,該格式由IEEE 754定義。這意味著,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);

未定義

[編輯 | 編輯原始碼]

僅宣告但未初始化為任何值的變數具有未定義資料型別。

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

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

符號表示唯一的識別符號。符號可能具有作為字串傳遞給其建構函式的描述符。

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

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

另請參閱

[編輯 | 編輯原始碼]

有關資料型別的 ECMAScript 定義

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

參考文獻

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