领先的免费Web技术教程,涵盖HTML到ASP.NET

网站首页 > 知识剖析 正文

TS 数据类型_下(tsp数据)

nixiaole 2025-03-24 18:53:10 知识剖析 5 ℃

symbol数据类型

//Symbol 不可变,且是唯一的
const a = Symbol("a")
const b = Symbol("a")

//a和b虽然封装了相同的值,但因为每个对象都是唯一的所以 返回false 
console.log(a === b)

//对比string
const strA = "abc"
const strB = "abc"
//返回true
console.log(strA === strB)

元组数据类型

//元组类型类似数组,但可以存储不同的数据类型,更像表中的一行数据
//readonly 代表该元组为只读
const row1 :readonly [number,string,string,string,number]= [1,"tom","China","beijing",22]
console.log(row1)
//根据索引访问特定的字段
console.log(row1[2])

//命名数组 类似给表中的列名,让程序更加可读
const row2 :readonly [id:number,name:string,nation:string,privice:string,age:number]= [1,"tom","China","beijing",22]
//输出元素所有的属性值
for (const element of row2){
 console.log(element)
}

数组数据类型

//数据是用来存储一组相同数据类型的值
//例如可以存储某个班级所有人的名字
const names:string[] = ["tom","jack"]
//输出数组中的所有内容
console.log(names)
//增加新元素 例如来了新同学
names.push("lucy")
console.log(names)
//修改元素,例如tom改成tomdog
names[0] = "tomdog"
console.log(names)
//查询谁的名字是4个字母,找到第一个就返回
const result =names.find((value) => value.length ==4)
console.log(result)
//查询所有名字是4个字母的数据
const result2 = names.filter((value) => value.length == 4)
console.log(result2)
//使用指定的符号连接数组的元素
const result3 = names.join("---")
console.log(result3)
//便利数组
names.forEach((value)=>{
    console.log("name is:" + value)
})
//填充数组,该值会覆盖当前数组的值
names.fill("nobody")
console.log(names)
//更多数组的方法可以参考官方文档

object 类型

//object类型是可以将不同的数据类型进行封装,类似java中的类
const obj = {
    name:"tom",
    age:11
}

console.log(obj.name)
console.log(obj.age)

//先定义类型,然后创建这个类型的对象
const person:{name:string,age:number} = {
    name:"lucy",
    age:11
}
console.log(person)

//可以在属性后面加?代表实例化这个对象的时候参数是可以选的
const person:{name:string,age?:number} = {
    name:"lucy",
}
console.log(person)

Tags:

最近发表
标签列表