如何在 JavaScript 中獲取字串的原始值?
在 JavaScript 中,如果資料不是物件並且沒有方法和屬性,則稱為原始資料型別或原始值。JavaScript 中不同型別的原始資料型別包括字串、數字、布林值、未定義、符號、空值和大整數。
布林值、字串和數字等原始型別可以由它們的包裝物件包裝,即分別為 Boolean、String 和 Number 建構函式的例項。
要從物件包裝器中獲取原始值,我們需要在物件上呼叫 valueOf() 方法。
示例
以下示例演示了布林值、字串和數字的原始型別和物件型別:
console.log("boolean :::::"); console.log("type of 'true': "+typeof true); console.log("type of 'new Boolean()': "+typeof new Boolean()); console.log("value of 'new Boolean(true)': "+new Boolean(true).valueOf()); console.log("string :::::"); console.log("type of 'abc': "+typeof "abc"); console.log("typeof 'new String()': "+typeof new String("abc")); console.log("value of 'new String('abc')': "+new String("abc").valueOf()); console.log("number :::::"); console.log("type of '123': "+typeof 123); console.log("type of 'new Number()': "+typeof new Number(123)); console.log("value of 'new Number(123)': "+new Number(123).valueOf());
字串的原始值
字串的原始值由 valueOf() 方法作為字串資料型別返回。
但是,對於 Number 型別的物件,function valueOf() { [native code] }() 返回物件表示的原始數值。類似地,它返回 Boolean 物件的原始布林值和 String 物件的字串。
很少需要直接呼叫此函式。當物件用於期望原始值的地方時,JavaScript 會自動執行此操作。
自動呼叫函式valueOf() { [native code] }(),區分原始值及其對應的物件比較困難。例如,typeof() 運算子區分字串和 String 物件,但在實踐中,您可以在 JavaScript 程式碼中互換使用它們。
語法
valueOf() 語法如下:
stringName.valueOf()
valueOf() 方法不接受任何引數,並返回呼叫 String 物件的原始值,即字串本身。由於它返回字串,這意味著它不會將物件更改為字串,它只是返回給定物件的字串。
示例 1
以下是一個 valueOf() 函式的示例。在這裡,我們正在檢索 Sting 物件的值:
var str = new String('You are viewing this content in Tutorials Point Website'); console.log("The given input object with its type is:",str) console.log(typeof(str)); console.log("The primitive value of the given string object with its type is:",str.valueOf()) console.log(typeof(str.valueOf()));
示例 2
讓我們再看一個例子:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>valueOf()</title> </head> <body> <h3>The valueOf() Method - Strings</h3> <p>The valueOf() method will return the primitive value of the string in JS</p> <p id="d"></p> <script> let tp = new String("This tutorial is about valueOf() method and primitive values"); let res = tp.valueOf() document.getElementById("d").innerHTML = res +"<br/>" + typeof(tp) +" returned as: " + typeof(res); </script> </body> </html>
廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP