本文共 2942 字,大约阅读时间需要 9 分钟。
数据类型是 JavaScript 中的核心概念,它决定了变量的类型和值的范围。以下是 JavaScript 中常见的数据类型及其使用方法。
let s: string = "Hello, World!";
let n: number = 3.14;
true 或 false。let b: boolean = true;
let variable: string;variable = null; // 变量被赋值为 null
const symbol: symbol = Symbol('mySymbol');数组是数据类型的扩展,用于存储多个同一类型的元素。
// 创建字符串数组let arr1: string[] = ['a', 'b', 'c'];// 创建数值数组let arr2: Array= [1, 2, 3, 4, 5];// 创建元祖let tuple: [string, number] = ['a', 1];// 创建带有联合类型的数组let arr3: (string | number)[] = ['a', 1];// 使用 any 类型创建灵活数组let anyList: any[] = ['a', 1, true];
枚举类型允许代码更安全地处理常量。
enum Directions { left = 2, right, top, bottom}console.log(Directions.top); // 输出: topconsole.log(Directions[2]); // 输出: left 对象是 JavaScript 中用于创建复杂数据结构的核心。
interface LabelledValue { label: string;}function printLabel(labelledObj: LabelledValue) { console.log(labelledObj.label);}let myObj = { size: 10, label: "Size 10 Object" };printLabel(myObj); 函数是 JavaScript 中的核心概念,用于定义代码逻辑。
function add(x: number, y: number): number { return x + y;}let myAdd = function(x: number, y: number): number { return x + y;} 类与接口结合使用,用于构建复杂的对象结构。
class Person { name: string; age: number; constructor(name: string, age: number) { this.name = name; this.age = age; } getName(): string { return this.name; }} 抽象类是类的一种特殊形式,用于定义抽象属性和方法。
abstract class Animal { abstract type: string; name: string; constructor(name: string) { this.name = name; } abstract getType(): string; getName(): string { return this.name; }}class Dog extends Animal { type: string; constructor(name: string, type: string) { super(name); this.type = type; } getType(): string { return this.type; }} 接口用于定义对象的公共属性和方法的契约。
interface Girl { name: string; age: number; loveYou(): void;}class GrilFriend implements Girl { name: string; age: number; constructor(name: string, age: number) { this.name = name; this.age = age; } loveYou(): void { console.log("Her name is " + this.name + ", her age is " + this.age); }}let gf = new GrilFriend("Linda", 28);gf.loveYou(); 泛型是 JavaScript 中的高级特性,用于创建可扩展的函数和类。
// 泛型函数function showData(person: T): T { return person;}showData ("Lucy");// 泛型函数接口interface GenericIdentityFn { (arg: T): T;}function identity(arg: T): T { return arg;}let myIdentity: GenericIdentityFn = identity;
泛型类允许类的实例部分使用任意类型。
class GenericNumber{ zeroValue: T; add: (x: T, y: T) => T;}let myGenericNumber = new GenericNumber ();myGenericNumber.zeroValue = 0;myGenericNumber.add = function(x, y) { return x + y;};
通过以上内容,可以清晰地了解 JavaScript 中的数据类型、函数、类和接口等核心概念,以及如何利用这些概念构建复杂的应用程序。
转载地址:http://movq.baihongyu.com/