Javascript Type Conversion

9 min read

Number() converts to a Number, String() converts to a String, Boolean() converts to a Boolean.

Number () нь тоо руу, String () нь String руу, Boolean () нь Boolean руу хөрвүүлнэ.


JavaScript Data Types #

In JavaScript there are 5 different data types that can contain values:

JavaScript дээр утга агуулж болох 5 өөр өгөгдлийн төрөл байдаг:

  • string
  • number
  • boolean
  • object
  • function

There are 6 types of objects:

6 төрлийн объект байдаг:

  • Object
  • Date
  • Array
  • String
  • Number
  • Boolean

And 2 data types that cannot contain values:

Мөн утга агуулаагүй 2 өгөгдлийн төрөл:

  • null
  • undefined

The typeof Operator #

You can use the typeof operator to find the data type of a JavaScript variable.

Та JavaScript хувьсагчийн өгөгдлийн төрлийг олохын тулд typeof операторыг ашиглаж болно.

Example Жишээ #

typeof "John" // Returns "string" typeof 3.14 // Returns "number" typeof NaN // Returns "number" typeof false // Returns "boolean" typeof [1,2,3,4] // Returns "object" typeof {name:'John', age:34} // Returns "object" typeof new Date() // Returns "object" typeof function () {} // Returns "function" typeof myCar // Returns "undefined" * typeof null // Returns "object"

Please observe:

Анхаарна уу:

  • The data type of NaN is number

    NaN-ийн өгөгдлийн төрөл нь тоо юм

  • The data type of an array is object

    Массивын өгөгдлийн төрөл нь объект юм

  • The data type of a date is object

    Огнооны өгөгдлийн төрөл нь объект юм

  • The data type of null is object

    Null-ийн өгөгдлийн төрөл нь объект юм

  • The data type of an undefined variable is undefined *

    Тодорхойгүй хувьсагчийн өгөгдлийн төрөл нь тодорхойгүй байна *

  • The data type of a variable that has not been assigned a value is also undefined *

    Утга өгөөгүй хувьсагчийн өгөгдлийн төрөл бас тодорхойгүй байна *

You cannot use typeof to determine if a JavaScript object is an array (or a date).

Та JavaScript объект нь багц (эсвэл огноо) эсэхийг тодорхойлохын тулд typeof-ийг ашиглаж чадахгүй.


 
 
 
 
 
 
 
 
 

The Data Type of typeof #

Өгөгдлийн төрөл #

The typeofoperator is not a variable. It is an operator. Operators ( + – * / ) do not have any data type.

typeofoperator нь хувьсагч биш юм. Энэ бол оператор юм. Операторуудад (+ – * /) өгөгдлийн төрөл байхгүй байна.

But, the typeof operator always returns a string (containing the type of the operand).

Гэхдээ typeof оператор нь үгийг буцааж өгдөг (операндын төрлийг агуулсан).


The constructor Property #

Байгуулагчийн өмч #

The constructor property returns the constructor function for all JavaScript variables.

constructor шинж чанар нь бүх JavaScript хувьсагчдын хувьд байгуулагчийн функцийг буцаадаг.

Example Жишээ #

"John".constructor // Returns function String() {[native code]} (3.14).constructor // Returns function Number() {[native code]} false.constructor // Returns function Boolean() {[native code]} [1,2,3,4].constructor // Returns function Array() {[native code]} {name:'John',age:34}.constructor // Returns function Object() {[native code]} new Date().constructor // Returns function Date() {[native code]} function () {}.constructor // Returns function Function(){[native code]}

You can check the constructor property to find out if an object is an Array (contains the word “Array”):

Та объектын Array мөн эсэхийг (“Багц” гэсэн үг агуулсан) олж мэдэхийн тулд байгуулагчийн шинж чанарыг шалгаж болно.

Example Жишээ #

function isArray(myArray) { return myArray.constructor.toString().indexOf("Array") > -1; }

Or even simpler, you can check if the object is an Array function:

Эсвэл бүр хялбар бол та объект Array функц мөн эсэхийг шалгаж болно:

Example Жишээ #

function isArray(myArray) { return myArray.constructor === Array; }

You can check the constructor property to find out if an object is a Date (contains the word “Date”):

Та объектын Date  (“Огноо” гэсэн үг агуулсан) эсэхийг мэдэхийн тулд байгуулагчийн шинж чанарыг шалгаж болно.

Example Жишээ #

function isDate(myDate) { return myDate.constructor.toString().indexOf("Date") > -1; }

Or even simpler, you can check if the object is a Date function:

Эсвэл бүр хялбар бол тухайн объект нь Date функц мөн эсэхийг шалгаж болно:

Example Жишээ #

function isDate(myDate) { return myDate.constructor === Date; }

JavaScript Type Conversion #

JavaScript төрөл хөрвүүлэлт #

JavaScript variables can be converted to a new variable and another data type:

JavaScript хувьсагчуудыг шинэ хувьсагч болон өөр өгөгдлийн төрөлд хөрвүүлэх боломжтой.

  • By the use of a JavaScript function

    JavaScript функцийг ашиглах замаар

  • Automatically by JavaScript itself

    JavaScript өөрөө автоматаар


Converting Numbers to Strings #

Тоонуудыг үг болгон хөрвүүлэх #

The global method String() can convert numbers to strings.

Глобал арга String() нь тоонуудыг мөр болгон хөрвүүлэх боломжтой.

It can be used on any type of numbers, literals, variables, or expressions:

Үүнийг ямар ч төрлийн тоо, үсэг, хувьсагч эсвэл илэрхийлэлд ашиглаж болно.

Example Жишээ #

String(x) // returns a string from a number variable x String(123) // returns a string from a number literal 123 String(100 + 23) // returns a string from a number from an expression

The Number method toString() does the same.

toString() тооны арга нь мөн адил хийгддэг.

Example Жишээ #

x.toString() (123).toString() (100 + 23).toString()

In the chapter Number Methods, you will find more methods that can be used to convert numbers to strings:

Тооны аргууд бүлгээс тоонуудыг үг болгон хөрвүүлэхэд ашиглаж болох илүү олон аргуудыг олох болно.

Method Description
toExponential() Returns a string, with a number rounded and written using exponential notation.

Дугуйруулж, экспоненциал тэмдэглэгээ ашиглан бичсэн үгийг буцаана.

toFixed() Returns a string, with a number rounded and written with a specified number of decimals.

Тоог бөөрөнхийлж, заасан аравтын бутархай тоогоор бичсэн үгийг буцаана.

toPrecision() Returns a string, with a number written with a specified length

Тодорхой уртаар бичсэн дугаар бүхий үгийг буцаана


Converting Booleans to Strings #

The global method String() can convert booleans to strings.

Глобал арга String() нь booleans-ийг үг болгон хувиргаж чаддаг.

String(false) // returns "false" String(true) // returns "true"

The Boolean method toString() does the same.

Boolean toString() арга нь мөн адил хийгддэг.

false.toString() // returns "false" true.toString() // returns "true"

Converting Dates to Strings #

Огноог үг болгон хувиргаж байна #

The global method String() can convert dates to strings.

Глобал арга String() нь огноог үг болгон хөрвүүлэх боломжтой.

String(Date()) // returns "Thu Jul 17 2014 15:38:19 GMT+0200 (W. Europe Daylight Time)"

The Date method toString() does the same.

toString() огнооны арга нь мөн адил хийгддэг.

Example Жишээ #

Date().toString() // returns "Thu Jul 17 2014 15:38:19 GMT+0200 (W. Europe Daylight Time)"

In the chapter Date Methods, you will find more methods that can be used to convert dates to strings:

Огнооны аргууд бүлгээс огноог үг болгон хөрвүүлэхэд ашиглаж болох илүү олон аргуудыг олох болно.

Method Description
getDate() Get the day as a number (1-31)

Өдрийг тоогоор авна уу (1-31)

getDay() Get the weekday a number (0-6)

Ажлын өдрийн дугаарыг авна уу (0-6)

getFullYear() Get the four digit year (yyyy)

Дөрвөн оронтой оныг аваарай (yyyy)

getHours() Get the hour (0-23)

Цаг авах (0-23)

getMilliseconds() Get the milliseconds (0-999)

Милисекундийг авах (0-999)

getMinutes() Get the minutes (0-59)

Минут авах (0-59)

getMonth() Get the month (0-11)

Сар авах (0-11)

getSeconds() Get the seconds (0-59)

Секунд аваарай (0-59)

getTime() Get the time (milliseconds since January 1, 1970)

Цаг авах (1970 оны 1-р сарын 1-ээс хойш миллисекунд)


Converting Strings to Numbers #

Үгнүүдийг тоонд шилжүүлэх #

The global method Number() can convert strings to numbers.

Глобал арга Number() нь үгнүүдийг тоонууд руу хөрвүүлэх боломжтой.

Strings containing numbers (like “3.14”) convert to numbers (like 3.14).

Тоо агуулсан үгнүүд (“3.14” гэх мэт) тоонууд руу шилждэг (3.14 гэх мэт).

Empty strings convert to 0.

Хоосон үгнүүд 0 болж хувирдаг.

Anything else converts to NaN (Not a Number).

Бусад бүх зүйл NaN (тоо биш) болж хувирдаг.

Number("3.14") // returns 3.14 Number(" ") // returns 0 Number("") // returns 0 Number("99 88") // returns NaN

In the chapter Number Methods, you will find more methods that can be used to convert strings to numbers:

Тооны аргууд бүлгээс үгнүүдийг тоонд хөрвүүлэхэд ашиглаж болох илүү олон аргуудыг олох болно.

Method Description
parseFloat() Parses a string and returns a floating point number

Үгийг ялгаж, хөвөгч цэгийн дугаарыг буцаана

parseInt() Parses a string and returns an integer

Үгийг ялгаж бүхэл тоог буцаана


The Unary + Operator #

The unary + operator can be used to convert a variable to a number:

Unary + операторыг хувьсагчийг тоонд хөрвүүлэхэд ашиглаж болно:

Example Жишээ #

var y = "5"; // y is a string var x = + y; // x is a number

If the variable cannot be converted, it will still become a number, but with the value NaN (Not a Number):

Хэрэв хувьсагчийг хөрвүүлэх боломжгүй бол энэ нь тоо болж хувирах боловч NaN (Тоо биш) гэсэн утгатай байна:

Example Жишээ #

var y = "John"; // y is a string var x = + y; // x is a number (NaN)

Converting Booleans to Numbers #

Булийн тоог тоонууд руу хөрвүүлэх #

The global method Number() can also convert booleans to numbers.

Глобал арга Number() нь booleans-ыг тоонд хөрвүүлэх боломжтой.

Number(false) // returns 0 Number(true) // returns 1

Converting Dates to Numbers #

Огноо дугаар руу хөрвүүлэх #

The global method Number() can be used to convert dates to numbers.

Глобал аргыг Number() ашиглан огноог тоонуудад хөрвүүлэхэд ашиглаж болно.

d = new Date(); Number(d) // returns 1404568027739

The date method getTime() does the same.

getTime() огнооны арга нь мөн адил хийгддэг.

d = new Date(); d.getTime() // returns 1404568027739

Automatic Type Conversion #

Автомат хэлбэрийн хөрвүүлэлт #

When JavaScript tries to operate on a “wrong” data type, it will try to convert the value to a “right” type.

JavaScript нь “буруу” өгөгдлийн төрөл дээр ажиллахыг оролдох үед утгыг “зөв” хэлбэрт шилжүүлэхийг оролдох болно.

The result is not always what you expect:

Үр дүн нь үргэлж таны хүлээж байгаа зүйл биш юм:

 
5 + null // returns 5 because null is converted to 0 "5" + null // returns "5null" because null is converted to "null" "5" + 2 // returns "52" because 2 is converted to "2" "5" - 2 // returns 3 because "5" is converted to 5 "5" * "2" // returns 10 because "5" and "2" are converted to 5 and 2

Automatic String Conversion #

Автомат үг хөрвүүлэлт #

JavaScript automatically calls the variable’s toString() function when you try to “output” an object or a variable:

JavaScript нь объект эсвэл хувьсагчийг “гаргах” гэж оролдох үед хувьсагчийн toString() функцийг автоматаар дууддаг.

document.getElementById("demo").innerHTML = myVar; // if myVar = {name:"Fjohn"} // toString converts to "[object Object]" // if myVar = [1,2,3,4] // toString converts to "1,2,3,4" // if myVar = new Date() // toString converts to "Fri Jul 18 2014 09:08:55 GMT+0200"

Numbers and booleans are also converted, but this is not very visible:

Тоонууд болон booleans-ыг хөрвүүлдэг боловч энэ нь төдийлөн харагдахгүй байна.

// if myVar = 123 // toString converts to "123" // if myVar = true // toString converts to "true" // if myVar = false // toString converts to "false"

JavaScript Type Conversion Table #

JavaScript төрөл хөрвүүлэх хүснэгт #

This table shows the result of converting different JavaScript values to Number, String, and Boolean:

Энэ хүснэгтэд өөр өөр JavaScript утгыг Number, String, Boolean болгон хөрвүүлсний үр дүнг харуулав.

Original
Value
Converted
to Number
Converted
to String
Converted
to Boolean
 
false 0 “false” false  
true 1 “true” true  
0 0 “0” false  
1 1 “1” true  
“0” 0 “0” true  
“000” 0 “000” true  
“1” 1 “1” true  
NaN NaN “NaN” false  
Infinity Infinity “Infinity” true  
-Infinity -Infinity “-Infinity” true  
“” 0 “” false  
“20” 20 “20” true  
“twenty” NaN “twenty” true  
[ ] 0 “” true  
[20] 20 “20” true  
[10,20] NaN “10,20” true  
[“twenty”] NaN “twenty” true  
[“ten”,”twenty”] NaN “ten,twenty” true  
function(){} NaN “function(){}” true  
{ } NaN “[object Object]” true  
null 0 “null” false  
undefined NaN “undefined” false  

Values in quotes indicate string values.

Ишлэл дэх утга нь үгийн утгыг заана.

Red values indicate values (some) programmers might not expect.

Улаан утга нь програмистуудын хүлээж чадахгүй утгыг (зарим) илэрхийлдэг.

Powered by BetterDocs

Leave a Reply