TypeScript及JavaScript 基础语法

JavaScript 基础语法

1. 变量声明

// const - 常量(不能重新赋值)
const name = "Alice";
const numbers = [1, 2, 3];

// let - 可变变量
let count = 0;
count = 1;  // ✅ 可以修改

// var - 不推荐使用(有作用域问题)
var oldWay = "avoid this";

2. 数据类型

// 基本类型
const str: string = "hello";
const num: number = 42;
const bool: boolean = true;
const arr: number[] = [1, 2, 3];

// 类型可以推断(不需要显式声明)
const inferred = "TypeScript knows this is a string";

3. 函数

// 普通函数
function add(a: number, b: number): number {
  return a + b;
}

// 箭头函数(更简洁)
const multiply = (a: number, b: number): number => {
  return a * b;
};

// 简写箭头函数
const square = (x: number) => x * x;

// 异步函数(返回 Promise)
async function fetchData(url: string): Promise<string> {
  const response = await fetch(url);
  return await response.text();
}

4. 对象

// 创建对象
const person = {
  name: "Alice",
  age: 30,
  greet() {
    console.log(`Hello, I'm ${this.name}`);
  }
};

// 访问属性
console.log(person.name);      // 点表示法
console.log(person["age"]);    // 方括号表示法

// 对象解构
const { name, age } = person;

5. 类(Class)

class Person {
  name: string;
  age: number;

  constructor(name: string, age: number) {
    this.name = name;
    this.age = age;
  }

  greet() {
    console.log(`Hello, I'm ${this.name}`);
  }
}

const alice = new Person("Alice", 30);
alice.greet();

6. 数组方法

const numbers = [1, 2, 3, 4, 5];

// map - 转换数组
const doubled = numbers.map(n => n * 2);  // [2, 4, 6, 8, 10]

// filter - 过滤数组
const evens = numbers.filter(n => n % 2 === 0);  // [2, 4]

// forEach - 遍历
numbers.forEach(n => console.log(n));

// find - 查找
const found = numbers.find(n => n > 3);  // 4

// reduce - 归约
const sum = numbers.reduce((acc, n) => acc + n, 0);  // 15

7. 条件语句

// if-else
if (age >= 18) {
  console.log("Adult");
} else {
  console.log("Minor");
}

// 三元运算符
const status = age >= 18 ? "adult" : "minor";

// switch
switch (day) {
  case "Monday":
    console.log("Start of week");
    break;
  default:
    console.log("Other day");
}

8. 循环

// for 循环
for (let i = 0; i < 5; i++) {
  console.log(i);
}

// for...of(遍历数组)
for (const item of [1, 2, 3]) {
  console.log(item);
}

// for...in(遍历对象属性)
const obj = { a: 1, b: 2 };
for (const key in obj) {
  console.log(key, obj[key]);
}

// while 循环
while (count < 10) {
  count++;
}

9. 异常处理

try {
  const result = riskyOperation();
  console.log(result);
} catch (error) {
  console.error("Error:", error.message);
} finally {
  console.log("Always executes");
}

// 抛出错误
throw new Error("Something went wrong");

10. 模板字符串

const name = "Alice";
const age = 30;

// 使用反引号
const message = `Hello, I'm ${name} and I'm ${age} years old`;

// 多行字符串
const html = `
  <div>
    <h1>${name}</h1>
    <p>Age: ${age}</p>
  </div>
`;

11. JSON 操作

// 对象转 JSON 字符串
const obj = { name: "Alice", age: 30 };
const jsonString = JSON.stringify(obj);
// → '{"name":"Alice","age":30}'

// JSON 字符串转对象
const parsed = JSON.parse(jsonString);
// → { name: "Alice", age: 30 }

// 格式化输出
const pretty = JSON.stringify(obj, null, 2);
/*
{
  "name": "Alice",
  "age": 30
}
*/

12. Fetch API(网络请求)

// GET 请求
async function getData(url: string) {
  const response = await fetch(url);
  const data = await response.json();
  return data;
}

// POST 请求
async function postData(url: string, data: object) {
  const response = await fetch(url, {
    method: "POST",
    headers: {
      "Content-Type": "application/json"
    },
    body: JSON.stringify(data)
  });
  return await response.json();
}

13:export default:

在一些平台中每个 .ts 文件是一个模块,export default就是告诉平台主要功能从哪里开始运行。

14:调试基础:

export default {
  async fetch(req) {
    const out = {
      runtime_type: typeof __runtime,
      runtime_keys: Object.getOwnPropertyNames(__runtime).sort(),
      runtime_symbols: Object.getOwnPropertySymbols(__runtime).map(String),
    };
    return new Response(JSON.stringify(out, null, 2), {
      headers: { "content-type": "application/json" },
    });
  },
};

Object.getOwnPropertyNames(__runtime)

  • 返回对象“自身”的属性名
  • 只返回字符串键
  • 包括不可枚举属性
  • 不会往原型链上找

Object.keys :只返回“可枚举的字符串键”

sort():数组排序,原地修改

Symbol:是 JavaScript 的第7种基本数据类型(ES6 新增),用于创建唯一的标识符。常用于创建隐藏属性

Object.getOwnPropertySymbols(__runtime):单独枚举 symbol 键,是因为有些内部能力喜欢藏在 symbol 属性上。

JSON.stringify(out, null, 2):把 JavaScript 值转成 JSON 字符串。

三个参数分别表示:

  • 要序列化的值
  • replacer,这里传 null 表示不用自定义处理
  • 缩进空格数,这里传 2 表示格式化输出

一些其他api:

下面是最重要的几个:

API 返回什么 会不会漏隐藏属性 会不会拿到 symbol
Object.keys(obj) 自身的可枚举字符串键 不会
Object.getOwnPropertyNames(obj) 自身的所有字符串键 不容易漏 不会
Object.getOwnPropertySymbols(obj) 自身的所有 symbol 键 不容易漏
Reflect.ownKeys(obj) 自身的所有键 最完整
export default {
  async fetch(req) {
    const targets = {
      runtime: __runtime,
      internal: __runtime._internal,
      lib: __runtime._internal.lib,
      symbols: __runtime._internal.lib.symbols,
      secrets: __runtime._secrets,
    };

    const out = {};
    for (const [name, obj] of Object.entries(targets)) {
      const keys = Reflect.ownKeys(obj || {}).map((k) =>
        typeof k === "symbol" ? k.toString() : k
      );
      out[name] = { keys };
    }

    return new Response(JSON.stringify(out, null, 2), {
      headers: { "content-type": "application/json" },
    });
  },
};

Object.entries(obj) 会返回一个数组,数组里每项都是 [key, value]

例如:

Object.entries({ a: 1, b: 2 })
// [["a", 1], ["b", 2]]

属性描述符:

在 JavaScript 里,一个属性不只是“有值”这么简单,它还有元信息:

  1. value
  2. writable
  3. enumerable
  4. configurable
  5. 或者 get
  6. 或者 set

可以用:

Object.getOwnPropertyDescriptor(obj, "x")

来看某个属性的描述符。

例:

const obj = {};
Object.defineProperty(obj, "hidden", {
  value: 123,
  enumerable: false,
  writable: false,
  configurable: false,
});

Object.getOwnPropertyDescriptor(obj, "hidden");

返回:

const obj = {};
Object.defineProperty(obj, "hidden", {
  value: 123,
  enumerable: false,
  writable: false,
  configurable: false,
});

Object.getOwnPropertyDescriptor(obj, "hidden");

十六进制解码器:

function hexToAscii(hex) {
  return hex
    .match(/../g)
    .map((h) => String.fromCharCode(parseInt(h, 16)))
    .join("");
}

hexToAscii("72656164"); // "read"
hexToAscii("6c697374"); // "list"

这里你又能顺便学到几个函数:

  • match(/../g):每两个字符切一组
  • parseInt(h, 16):按十六进制解析字符串
  • String.fromCharCode(...):把字符编码转成字符
  • join(""):把数组拼成字符串

TextEncoderTextDecoder:将字符串跟字节数组转换

例:

const encoder = new TextEncoder();
const bytes = encoder.encode("ABC"); 
const decoder = new TextDecoder();
const text = decoder.decode(bytes);

高频函数 / 语法速查表

写法 作用 你应该怎么记
export default ... 默认导出模块内容 平台要拿你的入口对象
async fetch(req) {} 异步方法 Worker 入口函数
new Response(body, init) 构造 HTTP 响应 你的返回值
await fetch(url, options) 发请求并等待结果 Web API,不是入口函数
typeof x 看值的大类类型 先确认对象存在与否
Object.getOwnPropertyNames(obj) 枚举自有字符串键 探隐藏属性常用
Object.getOwnPropertySymbols(obj) 枚举 symbol 键 防止漏掉 symbol
Reflect.ownKeys(obj) 枚举全部自有键 最完整
Object.entries(obj) 得到 [key, value] 数组 方便循环批处理
.map(fn) 映射数组 批量转换输出
.sort() 排序数组 稳定输出
JSON.stringify(x, null, 2) 转漂亮 JSON 适合做探针回显
try { ... } catch (e) { ... } 捕获异常 调未知函数必备
String(e) 把错误转字符串 稳定输出异常
obj | | {}
out[name] = value 动态设置属性 变量当键名时必须用
new TextEncoder().encode(s) 文本转字节 对接底层 binary API
暂无评论

发送评论 编辑评论


				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇
下一篇