本文介绍: TypeScript 对象是包含一组键值对的实例。key1 : “value1″ , // 标量 key2 : “value” , key3 : function() {// 函数 } , key4 : [ “content1″ , “content2″ ] //集合 } //访问对象 object_name . key1 // value1 object_name . key4 // [“content1″, “content2″]
1.定义
TypeScript 对象是包含一组键值对的实例。 值可以是标量、函数、数组、对象等,如下实例:
var object_name = {
key1: "value1", // 标量
key2: "value",
key3: function() {
// 函数
},
key4:["content1", "content2"] //集合
}
//访问对象
object_name.key1 // value1
object_name.key4 // ["content1", "content2"]
2.TypeScript 类型模板
var sites = {
site1: "",
site2: 0,
sayHello: function () { } // 类型模板
};
sites.site1 = "site1"
sites.site2 = 2
sites.sayHello = function () {
console.log("hello " + sites.site1 + sites.site2);
};
sites.sayHello(); // hello site1 2
3.为对象动态添加属性
let people = {
name: "hwm",
age: 18,
sayHello: ()=> {}
}
people.sex = "man"
3.1 解决方法
interface obj {
[idx: string]: any
}
let people: obj = {}
people.name = "hwm"
people.age = 18
console.log(people) // { name: 'hwm', age: 18 }
3.2 对象作为参数传递
方法一:
private ParamObj(objT: {name: string, age: number}) {
let people = objT
console.log(objT)
}
let people = {name: "hwm", age: 18}
this.ParamObj(people) // {name: "hwm", age: 18}
方法二:
interface obj {
[idx: string]: any
}
private ParamObj(objT: obj) {
let people = objT
console.log(objT)
}
let people:obj = {}
people.name = "lll"
people.age = 20
this.ParamObj(people) // {name: "lll", age: 20}
3.3 方法返回对象
private ReturnObj(): {name: string, age: number}{
let people = {name: "hwm", age: 18}
return people
}
let res = this.ReturnObj()
console.log(res) // {name: "hwm", age: 18}
3.4 对象数组
let tbl: {name: string, age: number}[] = []
原文地址:https://blog.csdn.net/weixin_45136016/article/details/130287207
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如若转载,请注明出处:http://www.7code.cn/show_30742.html
如若内容造成侵权/违法违规/事实不符,请联系代码007邮箱:suwngjj01@126.com进行投诉反馈,一经查实,立即删除!
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。