ts中的对象和接口
//ts中的对象 一组相关属性和方法的集合,元素无序
let person = {}//空对象,对象中的属性存储为键值对。多个键值对用逗号分隔
console.log(person)
person = {
name:'caocao',
age:22,
sayhi: function (){
console.log("i am doing something")
}
}
console.log(person)
let animal : {//对象类型注解
name:string;
year:number;
}
animal = {//赋值需要在声明类型之后
name : "kk",
year : 22
}
console.log(animal.name)
let sing:{//对象类型注解,约束属性类型及方法返回值类型
autroth:string;
singasong:(song:string)=>string
}
sing={
autroth:"sdfddd",
singasong:function (song:string){
return song
}
}
console.log(sing.singasong("you look nice"))
//接口的使用
interface ImInterface{
name:string;
age: number;
}
//复用接口注解 接口名称约定大写I开头
let p1:ImInterface = {
name:"gongyu",
age: 66
}
let p2:ImInterface = {
name:"lindddaklk",
age:888
}
p2.age = 666//修改对象的属性值
console.log(p2.age)
forEach 回调函数遍历数组
let songs:string[] = ['miya','minglan','wangbadan']
let len:number = songs.length
console.log("长度",len)
const count = songs.push('nihao')//数组末尾追加元素,并返回新数组的长度
console.log("数组新长度",count)
//forEach遍历数组
songs.forEach(//循环中为回调函数可以拿到数组中的元素信息
function(item,index){
console.log("元素:",item,"下标",index)
}
)
let nums:number[] = [33,0,-88,66,44445]
//判断练习,判断是否有大于50的元素
nums.forEach(element => {
if(element>50){
console.log(element)
}
});
//有些场景为遍历数组,判断数组中是否有满足条件的元素,
//不必要全部遍历完,遇到存在则返回,停止循环
//forEach遍历时是全部遍历,some可以做到满足条件则停止循环,
let nums:number[] = [33,0,-88,66,44445]
//判断元素是否有元素小于0
nums.some(function(item){
console.log(item)
if(item<0){
return true
}
return false
})
类型推论
//类型推论
let a = 18 //此时ts默认推论a 类型为number
let b
b = 111//此时无类型推论,声明时应该手动指定类型
let c:number
c=33 //规范写法
function sum(n1:number,n2:number){//此时方法根据返回值类型发生类型推论,不必要手动指定
return n1+n2
}