【TypeScript】内置对象

JavaScript 中很多内置对象,可以直接在 TypeScript 中当做定义好了的类型。

ECMAScript 的内置对象

Boolean、Number、String、RegExp、Date、Error、XMLHttpRequest 等

let num: Number = new Number(1)
let date: Date = new Date()
let reg: RegExp = new RegExp(/\w/)
let error: Error = new Error('错误')
let xhr: XMLHttpRequest = new XMLHttpRequest()
let str:String = new String()

DOM 和 BOM 的内置对象

Document、HTMLElement、Event、NodeList 等

// DOM:

// HTML(元素名称)Element
let div: HTMLDivElement = document.querySelector('div')
let cvs: HTMLCanvasElement = document.querySelector('canvas')

// HTMLElement
let sec: HTMLElement = document.querySelector('section')
let footer: HTMLElement = document.querySelector('footer')
// 或者直接断言为 Element :
let header = document.querySelector('header') as Element

// 获取集合,NodeList 支持 forEach 遍历获取每一个节点
let div1:NodeList = document.querySelectorAll('div')
// 类型不固定
let div2:NodeListOf<HTMLDivElement | HTMLElement> = document.querySelectorAll('div footer')
// BOM:

let local:Storage = localStorage
let lct: Location = location
let promise:Promise<number> = new Promise((r)=>r(1))
let cookie:string = document.cookie

实例-代码雨

index.ts

let canvas = document.querySelector('#canvas') as HTMLCanvasElement
let ctx = canvas.getContext('2d') as CanvasRenderingContext2D
canvas.height = screen.availHeight; //可视区域的高度
canvas.width = screen.availWidth; //可视区域的宽度
let str: string[] = '010101010101'.split('')
let Arr = Array(Math.ceil(canvas.width / 10)).fill(0) //获取宽度例如1920 / 10 192
console.log(Arr);
 
const rain = () => {
    ctx.fillStyle = 'rgba(0,0,0,0.05)'//填充背景颜色
    ctx.fillRect(0, 0, canvas.width, canvas.height)//背景
    ctx.fillStyle = "#0f0"; //文字颜色
    Arr.forEach((item, index) => {
        ctx.fillText(str[ Math.floor(Math.random() * str.length) ], index * 10, item + 10)
        Arr[index] = item >= canvas.height || item > 10000 *  Math.random() ? 0 : item + 10; //添加随机数让字符随机出现不至于那么平整
    })
    console.log(Arr);
    
}
setInterval(rain, 40)

index,html

DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Documenttitle>
  <style>
    * {
      padding: 0;
      margin: 0;
      overflow: hidden;
    }

  style>
head>
<body>
  <canvas id="canvas" width="1200" height="1200">canvas>
  <script src="./index.js">script>
body>
html>

【TypeScript】内置对象_第1张图片

你可能感兴趣的:(TypeScript,typescript,ubuntu,javascript)