阿里云主机折上折
  • 微信号
Current Site:Index > Type conversion and detection

Type conversion and detection

Author:Chuan Chen 阅读数:23402人阅读 分类: JavaScript

The Concept of Type Conversion

Type conversion in JavaScript refers to the process of converting one data type to another. Since JavaScript is a weakly typed language, type conversion often occurs automatically during code execution or can be triggered explicitly. Understanding the mechanism of type conversion is crucial for avoiding potential errors.

let num = 42;
let str = String(num); // Explicit conversion to string
console.log(typeof str); // "string"

let result = "5" * 2; // Implicit conversion to number
console.log(result); // 10

Implicit Type Conversion

Implicit type conversion is performed automatically by the JavaScript engine, typically during operator operations or comparisons.

Conversion in Arithmetic Operations

console.log("10" - 5); // 5, string converted to number
console.log("10" + 5); // "105", number converted to string
console.log(true + 1); // 2, boolean converted to number

Conversion in Comparison Operations

console.log("5" == 5); // true, string converted to number for comparison
console.log("" == false); // true, empty string and false both converted to 0
console.log(null == undefined); // true, special rule

Explicit Type Conversion

Developers can actively use various methods for type conversion.

Converting to String

let num = 123;
let str1 = String(num);
let str2 = num.toString();
let str3 = num + "";

console.log(typeof str1, typeof str2, typeof str3); // all are string

Converting to Number

let str = "3.14";
let num1 = Number(str);
let num2 = +str;
let num3 = parseInt(str);
let num4 = parseFloat(str);

console.log(num1, num2, num3, num4); // all are 3.14 or 3

Converting to Boolean

console.log(Boolean(0)); // false
console.log(Boolean("")); // false
console.log(Boolean(null)); // false
console.log(Boolean(undefined)); // false
console.log(Boolean(NaN)); // false
console.log(Boolean("hello")); // true
console.log(Boolean(1)); // true

Type Detection Methods

Accurately determining variable types is a common requirement in development.

The typeof Operator

console.log(typeof 42); // "number"
console.log(typeof "text"); // "string"
console.log(typeof true); // "boolean"
console.log(typeof undefined); // "undefined"
console.log(typeof null); // "object" (historical artifact)
console.log(typeof []); // "object"
console.log(typeof {}); // "object"
console.log(typeof function(){}); // "function"

The instanceof Operator

let arr = [];
console.log(arr instanceof Array); // true
console.log(arr instanceof Object); // true

function Person() {}
let p = new Person();
console.log(p instanceof Person); // true

Object.prototype.toString

console.log(Object.prototype.toString.call(42)); // "[object Number]"
console.log(Object.prototype.toString.call("text")); // "[object String]"
console.log(Object.prototype.toString.call(true)); // "[object Boolean]"
console.log(Object.prototype.toString.call(null)); // "[object Null]"
console.log(Object.prototype.toString.call(undefined)); // "[object Undefined]"
console.log(Object.prototype.toString.call([])); // "[object Array]"
console.log(Object.prototype.toString.call({})); // "[object Object]"
console.log(Object.prototype.toString.call(function(){})); // "[object Function]"

Array.isArray()

console.log(Array.isArray([])); // true
console.log(Array.isArray({})); // false

Special Type Conversion Cases

Object-to-Primitive Conversion

let obj = {
  valueOf() {
    return 42;
  },
  toString() {
    return "custom object";
  }
};

console.log(obj + 1); // 43, `valueOf` is prioritized
console.log(String(obj)); // "custom object", `toString` is prioritized

Date Object Conversion

let date = new Date();
console.log(date.toString()); // "Wed May 01 2024 12:00:00 GMT+0800"
console.log(date.valueOf()); // Timestamp as a number
console.log(+date); // Timestamp as a number

JSON Conversion

let data = {
  name: "John",
  age: 30,
  toJSON() {
    return { name: this.name };
  }
};

console.log(JSON.stringify(data)); // '{"name":"John"}'

Best Practices for Type Conversion

Avoiding Pitfalls of Implicit Conversion

// Use strict equality to avoid type conversion
console.log("5" === 5); // false

// Make conversion intentions explicit
let input = "123";
let num = Number(input); // More explicit than +input
if (!isNaN(num)) {
  console.log("Valid number:", num);
}

Handling Edge Cases

// Handling possible null/undefined
function safeToString(value) {
  return value == null ? "" : String(value);
}

// Safe numeric conversion
function safeToNumber(value) {
  let num = Number(value);
  return isNaN(num) ? 0 : num;
}

Custom Type Conversion

class Temperature {
  constructor(celsius) {
    this.celsius = celsius;
  }
  
  valueOf() {
    return this.celsius;
  }
  
  toString() {
    return `${this.celsius}°C`;
  }
  
  [Symbol.toPrimitive](hint) {
    if (hint === "string") {
      return this.toString();
    }
    return this.valueOf();
  }
}

let temp = new Temperature(25);
console.log(temp + 5); // 30
console.log(String(temp)); // "25°C"

本站部分内容来自互联网,一切版权均归源网站或源作者所有。

如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn

上一篇:流程控制语句

下一篇:类数组对象

Front End Chuan

Front End Chuan, Chen Chuan's Code Teahouse 🍵, specializing in exorcising all kinds of stubborn bugs 💻. Daily serving baldness-warning-level development insights 🛠️, with a bonus of one-liners that'll make you laugh for ten years 🐟. Occasionally drops pixel-perfect romance brewed in a coffee cup ☕.