在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
class Greeter {
greeting: string;
constructor(message: string) {
this.greeting = message;
};
name:string="Henry";
uid:number=10086;
greet() {
return "Hello, " + this.greeting;
};
}
let greeter = new Greeter("world");
console.log(greeter.greet());
console.log("");
////===================for循环
console.log("=============== for");
var num:number = 5;
var i:number;
var result = 1;
for(i = num;i>=1;i--) {
result *= i;
}
console.log(result)
////===================for...in
console.log("=============== for...in");
var n:any = [1,2,3,4,5]
for(var j in n)
{
console.log("%d %d", j, n[j]);
}
//=============== for...of
console.log("=============== for...of");
let someArray = [1, "stringABCDE", false];
for(let entry of someArray)
{
console.log(entry); // 1, stringABCDE, false
}
//=============== forEach
console.log("=============== forEach");
let list = [4,5,6];
list.forEach((val, idx, array)=>{
// val: 当前值
// idx: 当前index
// array: Array
console.log("val:%d, idx:%d", val, idx);
console.log(array);
})
//=============== every
console.log("=============== every");
let list2 = [4,5,6];
list2.every((val, idx, array)=>{
// val: 当前值
// idx: 当前index
// array: Array
console.log("val:%d, idx:%d", val, idx);
console.log(array);
return true; //Contiunes
//Return false will quite the iteration
})
//=============== while
console.log("=============== while");
var num:number = 5;
var factorial:number = 1;
while(num >=1) {
factorial = factorial * num;
num--;
}
console.log("5 的阶乘为:"+factorial);
console.log("===================== function ================");
// 函数定义
function greet():string { // 返回一个字符串
return "call function : Hello World"
}
function caller() {
var msg = greet() // 调用 greet() 函数
console.log(msg)
}
// 调用函数
caller()
console.log("============ function ======= with para =========");
function add(x: number, y: number): number {
return x + y;
}
console.log(add(1,2))
console.log("===== function ==== 可选参数和默认参数 =========");
function calculate_discount(price:number,rate:number = 0.50) {
var discount = price * rate;
console.log("计算结果: ",discount);
}
calculate_discount(1000)
calculate_discount(1000,0.30)
console.log("===== function === 参数个数不确定 ========");
function buildName(firstName: string, ...restOfName: string[]) {
return firstName + " " + restOfName.join(" ");
}
let employeeName = buildName("Joseph", "Samuel", "Lucas", "MacKinzie");
console.log(employeeName);
function addNumbers(name:string, ...nums:number[]) {
var i;
var sum:number = 0;
console.log("%s,不定参数个数测试.", name);
for(i = 1;i<nums.length;i++) {
sum = sum + nums[i];
}
console.log("和为:",sum)
}
addNumbers("test1", 1,2,3)
addNumbers("test2",10,10,10,10,10)
//====================[匿名函数]==================
console.log("");
var msg = function() {
return "hello world.ni ming function.";
}
console.log("不带参 匿名函数: " + msg())
var res = function(a:number,b:number) {
return a*b;
};
console.log("带参数,匿名函数: " + res(12,2));
(function () {
var x = "Hello!!";
console.log("匿名函数自调:" + x)
})();
var myFunction = new Function("a", "b", "return a * b");
var x = myFunction(4, 3);
console.log("内置构造函数 定义函数: " + x);
function fibos_fun(num:number) :number{
if (num <= 0) { // 停止执行
return 1;
} else {
return (num + fibos_fun(num - 1)); // 调用自身
}
};
console.log("fibos_fun: " + fibos_fun(6)); // 输出 720
//============= Lambda函数,也成为箭头函数
// ( [param1, parma2,…param n] )=>statement;
var foo = (x:number)=>10 + x
console.log(foo(100)) //输出结果为 110
//Lambda函数 作为语句块 赋值给一个 变量
var fooA = (x:number)=> {
x = 10 + x
console.log(x)
}
fooA(100)
//=======================
var func = (x:any)=> {
if(typeof x=="number") {
console.log(x+" 是一个数字")
} else if(typeof x=="string") {
console.log(x+" 是一个字符串")
}
}
func(12)
func("Tom")
var disp =()=> {
console.log("Function invoked.无参的时候,可以设置空括号.");
}
disp();
//==================函数的重载
console.log("=======函数的重载======参数不同...");
function dispA(s1:string):void;
function dispA(n1:number,s1:string):void;
function dispA(x:any,y?:any) {
console.log(x);
console.log(y);
}
dispA("abc") ;// abc,undefined
dispA(1,"xyz");// 1,xyz
console.log("TypeScript Number 属性: ");
console.log("最大值为: " + Number.MAX_VALUE);
console.log("最小值为: " + Number.MIN_VALUE);
console.log("负无穷大: " + Number.NEGATIVE_INFINITY);
console.log("正无穷大:" + Number.POSITIVE_INFINITY);
console.log("");
// ////可以正常转为js,但是在vs下面有错误提示...
// function employee(id:number,name:string) {
// this.id = id
// this.name = name
// }
// var emp = new employee(123,"admin")
// console.log("添加 email 属性");
// employee.prototype.email = "[email protected]"
// console.log("员工号: "+emp.id)
// console.log("员工姓名: "+emp.name)
// console.log("员工邮箱: "+emp.email)
//========================== String
var str = new String( "This is string" );
console.log("str.constructor is:" + str.length)
// var strA1 = new String( "RUNOOB" );
// var strA2 = new String( "GOOGLE" );
// var strA3 = strA1.concat( strA2 );
// console.log("str1 + str2 : "+strA3) // RUNOOBGOOGLE
var strA4 = new String( "aThis is beautiful string" );
var index = strA4.localeCompare( "This is beautiful string");
console.log("localeCompare first :" + index ); // 0
var strA5 = "Runoob Google";
console.log(strA5.toLowerCase( )); // runoob google
var strA6 = "Runoob";
console.log(strA6.toString( )); // Runoob
var strA7 = "Runoob Google";
console.log(strA7.toUpperCase( )); // RUNOOB GOOGLE
//======================数组================
var sites:string[];
sites = ["Google", "Runoob", "Taobao"];
console.log(sites);
console.dir(sites);
var testB = ["abc", 1,2,3,"google"];
console.dir(testB);
testB[0] = testB[0] + 666;
testB[1] = testB[1] + 777;
console.dir(testB);
if(typeof(testB[0]=='string'))
{
console.log("testB[0] is string.");
}
else if(typeof(testB[0]=='number'))
{
console.log("testB[0] is number.");
}
if(typeof(testB[1]=='string'))
{
console.log("testB[1] is string.");
}
else if(typeof(testB[1]=='number'))
{
console.log("testB[1] is number.");
}
// [ 'abc666', 778, 2, 3, 'google' ]
var arr_names:number[] = new Array(4)
for(var i = 0; i<arr_names.length; i++) {
arr_names[i] = i * 2
console.log(arr_names[i])
};
console.dir(arr_names);
//=================
var sitesStr:string[] = new Array("Google","Runoob","Taobao","Facebook")
function dispStr(arr_sites:string[]) {
for(var i = 0;i<arr_sites.length;i++) {
console.log(arr_sites[i])
}
}
dispStr(sitesStr);
///数组的 foreach 属性
let numA = [7, 8, 9];
numA.forEach(function (value) {
console.log(value);
});
////
console.log("pop()删除数组最后面的一个元素");
var numbers = [1, 4, 9];
var element = numbers.pop();
console.log("element is : " + element ); // 9
var element = numbers.pop();
console.log("element is : " + element ); // 4
console.log("tuple----------->>>>");
var mytuple = [10,"Runoob"];
console.log(mytuple);
//=========================
console.log("----->>>联合类型<<<-------");
function disp_union(name:string|string[]) {
if(typeof name == "string") {
console.log(name)
} else {
var i;
for(i = 0;i<name.length;i++) {
console.log(name[i])
}
}
}
disp_union("Runoob")
console.log("输出数组....")
disp_union(["Runoob","Google","Taobao","Facebook"])
//=================接口
console.log("------------接口------------");
interface IPerson{
firstName:string,
lastName:string,
sayHi:()=>string
};
var customer:IPerson={
firstName:"Tom",
lastName:"Hanks",
sayHi:():string=>{return "Hi, there."}
};
customer.firstName = "henry";
console.log("customer 对象 ");
console.log(customer.firstName);
console.log(customer.lastName);
console.log(customer.sayHi());
var employee:IPerson={
firstName:"Jim",
lastName:"Blakes",
sayHi:():string=>{return "hello!!!!"}
};
console.log("Employee 对象 ");
console.log(employee.firstName);
console.log(employee.lastName);
console.log("==============联合类型和接口=============");
interface RunOptions {
program:string;
commandline:string[]|string|(()=>string);
}
// commandline 是字符串
var options:RunOptions = {program:"test1",commandline:"Hello"};
console.log(options.commandline)
// commandline 是字符串数组
options = {program:"test1",commandline:["Hello","World"]};
console.log(options.commandline[0]);
console.log(options.commandline[1]);
// commandline 是一个函数表达式
options = {program:"test1",commandline:()=>{return "**Hello World**";}};
var fn:any = options.commandline;
console.log(fn());
console.log("==========接口和数组==========");
interface namelist {
[index:number]:string
}
//var list2:namelist = ["John",1,"Bran"] // 错误元素 1 不是 string 类型
interface ages {
[index:string]:number
}
var agelist:ages = ["John",1,"Bran"];
agelist["John"] = 15 // 正确
// agelist[2] = "nine" // 错误
console.dir(agelist);
console.log("============单继承实例==========");
interface Person {
age:number
} ;
interface Musician extends Person {
instrument:string
} ;
var drummer = <Musician>{};
drummer.age = 27 ;
drummer.instrument = "Drums" ;
console.log("年龄: "+drummer.age);
console.log("喜欢的乐器: "+drummer.instrument);
var drummer2 = <Musician>{};
drummer2.age = 666
drummer2.instrument = "abcdefg"
console.log("年龄: "+drummer2.age);
console.log("喜欢的乐器: "+drummer2.instrument);
console.log("===========多继承实例========")
interface IParent1 {
v1:number
};
interface IParent2 {
v2:number
} ;
interface Child extends IParent1, IParent2 { } ;
var Iobj:Child = { v1:12, v2:23} ;
console.log("value 1: "+Iobj.v1+" value 2: "+Iobj.v2);
console.log("========== TypeScript类 ==========")
class Person{};
class Car {
// 字段
engine:string;
// 构造函数
constructor(engine:string) {
this.engine = engine
}
// 方法
disp():void {
console.log("发动机为 : "+this.engine)
}
}
var objCar = new Car("Engine 1");
objCar.disp();
objCar.engine = "Engine 2";
objCar.disp();
//============= 类继承 extend ============
class Shape {
Area:number
constructor(a:number) {
this.Area = a
}
}
class Circle extends Shape {
disp():void {
console.log("圆的面积: "+this.Area)
}
}
var obj = new Circle(223);
obj.disp()
console.log("==========继承类的方法重写==========");
class PrinterClass {
doPrint():void {
console.log("父类的 doPrint() 方法。")
}
}
class StringPrinter extends PrinterClass {
doPrint():void {
super.doPrint() // 调用父类的函数
console.log("子类的 doPrint()方法。")
}
}
var abc = new StringPrinter();
abc.doPrint();
class Encapsulate{
str1:string="hello"
private str2:string = "world"
};
var objEncapsulate = new Encapsulate();
console.log(objEncapsulate.str1);
//console.log(objEncapsulate.str2);
console.log("=========类和接口======");
interface ILoan {
interest:number
}
class AgriLoan implements ILoan {
interest:number
rebate:number
constructor(interest:number,rebate:number) {
this.interest = interest
this.rebate = rebate
}
}
var objAgri = new AgriLoan(10,1)
console.log("利润为 : "+objAgri.interest+",抽成为 : "+objAgri.rebate )
//=================TypeScript对象===============
var object_name = {
key0:123,
key1:"valu1" ,//标量
key2:"value2",
key3:function(){ //函数
console.log("object_name...key3..func");
},
key4:["content1", "content2", 1,2,3,4], //集合
key5:[1,2,3,4,5,6] //数组
};
// var obj_name1 JSON.parse(JSON.stringify(object_name));
// var obj_name2 JSON.parse(JSON.stringify(object_name));
// var obj_name3 JSON.parse(JSON.stringify(object_name));
// obj_name1.key0 = 999;
// obj_name1.key1 = "111";
// obj_name1.key2 = "222";
// obj_name2.key0 = 333;
// obj_name2.key1 = "444";
// obj_name2.key2 = "555";
// obj_name3.key0 = 666;
// obj_name3.key1 = "777";
// obj_name3.key2 = "888";
// console.log("obj_name--------->>>>>start");
// console.log(obj_name1);
// console.log(obj_name2);
// console.log(obj_name3);
// console.log("obj_name--------->>>>>end");
var siteA = {
site1:"Runoob",
site2:"Google"
};
//访问对象的值
console.log(siteA.site1);
console.log(siteA.site2);
console.log("如果一个命名空间在一个单独的 TypeScript 文件中,则应使用三斜杠 /// 引用它,语法格式如下:");
/// <reference path = "SomeFileName.ts" />
interface PersonT1 {
firstName: string;
lastName: string;
};
var personA = <PersonT1>{};
personA.firstName = "HenryA";
personA.lastName = "HeA";
var personB = <PersonT1>{};
personB.firstName = "HenryB";
personB.lastName = "HeB";
var personC = <PersonT1>{};
personC.firstName = "HenryC";
personC.lastName = "HeC";
console.dir(personA);
console.dir(personB);
console.dir(personC);
|
请发表评论