diff --git a/entry/src/main/ets/pages/BasicPage.ets b/entry/src/main/ets/pages/BasicPage.ets index 7a5ea8157f0a6bf821bf049ae1c55bcf22f2f08b..00671768a495e2986cf44bc84e19d93c0b6f6a01 100644 --- a/entry/src/main/ets/pages/BasicPage.ets +++ b/entry/src/main/ets/pages/BasicPage.ets @@ -13,15 +13,16 @@ * limitations under the License. */ /** - * Chapter 3: Variables and Declarations. + * 变量与声明 */ function variableDeclaration() { - // Declare variable with let. + // 使用let声明变量 let count: number = 0; + // 后续可重新赋值 count = 40; console.log(`count: ${count}`); - // Declare constant with const, can be assigned only once. + // 使用const声明常量 const MAX_COUNT: number = 100; console.log(`MAX_COUNT: ${MAX_COUNT}`); } @@ -29,9 +30,9 @@ function variableDeclaration() { variableDeclaration(); /** - * Chapter 4: Types. + * 类型 */ -// Primitive types. +// 基本类型 function primitiveTypes() { let a: number = 10; let b: number = a; @@ -39,24 +40,24 @@ function primitiveTypes() { console.log(`a: ${a}`); console.log(`b: ${b}`); - // number. + // number类型 let age: number = 20; let score: number = 90.5; console.log(`age: ${age}`); console.log(`score: ${score}`); - // string. - let s1: string = 'Hello!'; // Use single quotes for string literals in this code. + // string类型 + let s1: string = 'Hello!'; // 单引号字符串 console.log(s1); - let s2: string = "Hello, world!"; // Use double quotes for string literals in this code. + let s2: string = "Hello, world!"; // 双引号字符串 console.log(s2); let result: string = 'Success'; - let s3: string = `The result is ${result}`; // Use backtick for string interpolation. + let s3: string = `The result is ${result}`; // 模版字符串 console.log(s3); - // boolean. + // boolean类型 let isPhoneOn: boolean = true; let isSunny: boolean = true; let needUmbrella: boolean = false; @@ -68,9 +69,9 @@ function primitiveTypes() { primitiveTypes(); -// Reference types. +// 引用类型 function referenceTypes() { - // Object + // Object类型 let o1: Object = 'Alice'; let o2: Object = ['a', 'b']; let o3: Object = 1; @@ -79,16 +80,16 @@ function referenceTypes() { console.log(`o3: ${o3}`); let strObject: String = new String('ArkTS'); - let obj: Object = 'ArkTS'; + let obj: Object = 'ArkTS'; // 自动装箱为String对象 let str: string = 'ArkTS'; - console.log(`${str.length}`); - console.log(`${str.indexOf('T')}`); + console.log(`${str.length}`); // 5 + console.log(`${str.indexOf('T')}`); // 3 console.log(`strObject: ${strObject}`); console.log(`obj: ${obj}`); - // Array - let students: string[] = ['XiaoMing', 'XiaoZhang', 'XiaoWang', 'XiaoLi']; - console.log(students[0]); // Get element at index 0. + // 数组 + let students: string[] = ['XiaoMing', 'XiaoZhang', 'XiaoWang', 'XiaoLi']; // 创建数组 + console.log(students[0]); // 获取索引为0的元素 students.push('XiaoHong'); students.pop(); @@ -101,65 +102,65 @@ function referenceTypes() { referenceTypes(); -// Type system. +// 类型系统 function typeSystem() { - // Enum type. + // 声明枚举类型Color,提供Red、Green、Blue三种颜色 enum Color { Red, Green, Blue } - let fontColor: Color = Color.Red; + let fontColor: Color = Color.Red; // 直接使用Color.Red进行赋值 console.log(`fontColor: ${fontColor}`); - // Union type. + // 联合类型 let luckNum: number | string = 7; luckNum = 'seven'; console.log(`luckNum: ${luckNum}`); - // Type Aliases. - type Matrix = number[][]; // Define alias Matrix for a 2D array. + // 类型别名 + type Matrix = number[][]; // 定义二维数组的别名为Matrix let arr: Matrix = [[1, 2, 3]]; console.log(`arr: ${arr}`); - type NullableObject = Object | null; // Define alias NullableObject for a nullable object. + type NullableObject = Object | null; // 定义可为空的对象的别名为NullableObject let obj: NullableObject = null; console.log(`obj: ${JSON.stringify(obj)}`); - // Type safety. + // 类型安全 let name: string = 'XiaoMing'; - // name = 20; // Type 'number' is not assignable to type 'string'. + // name = 20; // 类型number不能赋值给类型string console.log(`name: ${name}`); - // Type inference. - let meaningOfLife = 42; // meaningOfLife is inferred as number. + // 类型推断 + let meaningOfLife = 42; // meaningOfLife会被推断为number类型 console.log(`meaningOfLife: ${meaningOfLife}`); - // Type inference. + // 类型断言 let anyValue: Object = 'ArkTS'; - let strValue: string = anyValue as string; // Assert as string. + let strValue: string = anyValue as string; // 断言为字符串 console.log(`strValue: ${strValue}`); } typeSystem(); /** - * Chapter 5: Operators. + * 操作符 */ -// Assignment operators. +// 赋值运算符 function assignmentOperators() { - // Basic assignment operator. + // 基本赋值运算符 let a = 10; - // Compound assignment operators. - a += 5; // Equivalent to a = a + 5; + // 复合赋值运算符 + a += 5; // 等价于 a = a + 5; console.log(`a: ${a}`); } assignmentOperators(); -// Comparison operators. +// 比较运算符 function compareLoose(a: string | number, b: string | number) { return a == b; } @@ -171,20 +172,20 @@ function compareStrict(a: string | number, b: string | number) { function comparisonOperators() { let a: number = 5; let b: string = '5'; - console.log(`5 == '5': ${compareLoose(a, b)}`); // 5 == '5': true (string converted to number). - console.log(`5 === '5': ${compareStrict(a, b)}`); // 5 === '5': false (different types). + console.log(`5 == '5': ${compareLoose(a, b)}`); // 5 == '5': true(字符串转为数字) + console.log(`5 === '5': ${compareStrict(a, b)}`); // 5 === '5': false(类型不同) } comparisonOperators(); -// Arithmetic operators. +// 算数运算符 function arithmeticOperators() { - // Unary operator. + // 一元运算符 let count = 5; - let result = count++; // Equivalent to: let result = count; count = count + 1; + let result = count++; // 等价于: let result = count; count = count + 1; console.log(`count: ${count}, result: ${result}`); - // Binary operators. + // 二元运算符 let a = 10; let b = 4; console.log(`${a} + ${b} = ${a + b}`); @@ -196,10 +197,10 @@ function arithmeticOperators() { arithmeticOperators(); -// Logical operators. +// 逻辑运算符 function logicalOperators() { - let a = false && true; // false (first condition is false, short-circuits). - let b = true || false; // true (first condition is true, short-circuits). + let a = false && true; // false(首个条件为false,直接短路) + let b = true || false; // true(首个条件为true,直接短路) let c = !false; // true. console.log(`a: ${a}`); console.log(`b: ${b}`); @@ -208,7 +209,7 @@ function logicalOperators() { logicalOperators(); -// Bitwise operators. +// 位运算符 function bitwiseOperators() { let a = 5; let b = 2; @@ -224,12 +225,12 @@ function bitwiseOperators() { bitwiseOperators(); /** - * Chapter 6: Null Safety. + * 空安全 */ function nullSafety() { - // let x: number = null; // Type 'null' is not assignable to type 'number'. - // let y: string = null; // Type 'null' is not assignable to type 'string'. - // let z: number[] = null; // Type 'null' is not assignable to type 'number[]'. + // let x: number = null; // 编译时错误 + // let y: string = null; // 编译时错误 + // let z: number[] = null; // 编译时错误 let x: number | null = null; x = 1; // ok. x = null; // ok. @@ -248,18 +249,19 @@ function nullSafetyWithIf(name: string | null) { nullSafetyWithIf('if'); -function nullSafetyWithOptionalChaining(name: string | null) { +function optionalChaining(name: string | null) { let len: number | undefined = name?.length; return len; } -nullSafetyWithOptionalChaining('optional chaining'); +optionalChaining('optional chaining'); -function nullSafetyWithAssertion(name: string | null): number { +function getLength(name: string | null): number { + // return name.length; // name可能为null return name!.length; } -nullSafetyWithAssertion('non-null assertion operator'); +getLength('non-null assertion operator'); function nullSafetyWithNullishCoalescingOperator() { let name: string | null = null; @@ -270,9 +272,9 @@ function nullSafetyWithNullishCoalescingOperator() { nullSafetyWithNullishCoalescingOperator(); /** - * Chapter 7: Statements. + * 语句 */ -// Conditional statements - if statement. +// if语句 function showIfStatements() { let hasTicket = true; if (hasTicket) { @@ -284,7 +286,7 @@ function showIfStatements() { showIfStatements(); -// Conditional statements - conditional expression. +// 条件表达式 function conditionalExpressions() { let hasTicket = true; let result = hasTicket ? 'Ticket verified!' : 'Entry prohibited!'; @@ -293,7 +295,7 @@ function conditionalExpressions() { conditionalExpressions(); -// Conditional statements - switch statement. +// switch语句 function showSwitchStatements() { let day = 6; switch (day) { @@ -323,60 +325,60 @@ function showSwitchStatements() { showSwitchStatements(); -// Loop statements - for. +// for语句 function showForStatements() { let students: string[] = ['XiaoMing', 'XiaoZhang', 'XiaoWang', 'XiaoLi']; - // Access elements via array index. + // 通过数组索引访问数组元素 for (let i = 0; i < students.length; i++) { - console.log(students[i]); // Print student info. + console.log(students[i]); // 打印学生信息 } } showForStatements(); -// Loop statements - for...of. +// for-of语句 function showForOfStatements() { let students: string[] = ['XiaoMing', 'XiaoZhang', 'XiaoWang', 'XiaoLi']; - // Get array elements directly. + // 直接获取数组元素 for (let student of students) { - console.log(student); // Print student info. + console.log(student); // 打印学生信息 } } showForOfStatements(); -// Loop statements - while. +// while语句 function showWhileStatements() { let students: string[] = ['XiaoMing', 'XiaoZhang', 'XiaoWang', 'XiaoLi']; - let index = 0; // Initialize index. - // Loop condition: index less than array length. + let index = 0; // 初始化索引 + // 循环条件:index小于数组长度 while (index < students.length) { - console.log(students[index]); // Print student info. - index++; // Increment index (critical! otherwise infinite loop). + console.log(students[index]); // 打印学生信息 + index++; // 索引自增(关键! 否则会无限循环) } } showWhileStatements(); -// Loop statements - do...while. +// do-while语句 function showDoWhileStatements() { - let students: string[] = ['XiaoMing', 'XiaoZhang', 'XiaoWang', 'XiaoLi']; // Student name array. - let index = 0; // Initialize index. + let students: string[] = ['XiaoMing', 'XiaoZhang', 'XiaoWang', 'XiaoLi']; + let index = 0; // 初始化索引 do { - console.log(students[index]); // Execute loop body first. + console.log(students[index]); // 先执行循环体中的语句 index++; - } while (index < students.length); // Then evaluate loop condition. + } while (index < students.length); // 然后判断循环控制表达式 } showDoWhileStatements(); -// Loop statements - break. +// break语句 function showBreakStatements() { let students: string[] = ['XiaoMing', 'XiaoZhang', 'XiaoWang', 'XiaoLi']; for (let i = 0; i < students.length; i++) { - console.log(students[i]); // Print student info. + console.log(students[i]); // 打印学生信息 if (students[i] === 'XiaoWang') { - break; // Terminate loop. + break; // 终止循环 } } @@ -384,48 +386,52 @@ function showBreakStatements() { label: while (true) { switch (x) { case 1: - // statements. - break label; // break. + // ... + break label; // 中断while语句 } } } showBreakStatements(); -// Loop statements - continue. +// continue语句 function showContinueStatements() { let students: string[] = ['XiaoMing', 'XiaoZhang', 'XiaoWang', 'XiaoLi']; for (let i = 0; i < students.length; i++) { if (students[i] === 'XiaoWang') { - continue; // Skip. + continue; // 跳出本次循环 } - console.log(students[i]); // Print student info. + console.log(students[i]); // 打印学生信息 } } showContinueStatements(); -// Exception handling - throw. +// throw语句 function checkAge(age: number) { if (age < 0) { throw new Error('Age cannot be negative'); } } -// Exception handling - try. +// try语句 try { - let result = checkAge(-5); // Operation that may throw an exception. + // 可能发生异常的语句 + let result = checkAge(-5); console.log(`result: ${result}`); } catch (error) { - console.error('Error:', error.message); // Handle exception. + // 异常处理 + console.error('Error:', error.message); } finally { - console.log('finally'); // Runs regardless of exception. + // 无论是否发生异常都会执行的代码 + console.log('finally'); } /** - * Chapter 8: Functions. + * 函数 */ -// Function declaration. +// 函数声明 +// 显示指定函数返回类型为字符串 function makeMilkTea(flavor: string, sweetness: string): string { return `A cup of ${flavor} milk tea with ${sweetness}`; } @@ -435,7 +441,7 @@ console.log(tea); let tea1 = makeMilkTea('passion fruit', 'full sugar'); console.log(tea1); -// Optional parameter. +// 可选参数 function makeMilkTeaWithOptional(flavor: string, sweetness?: string): string { const sweet = sweetness || 'full sugar'; return `A cup of ${flavor} milk tea with ${sweet}`; @@ -450,7 +456,7 @@ function makeMilkTeaWithOptionalUseDefault(flavor: string, sweetness: string = ' console.log(makeMilkTeaWithOptionalUseDefault('strawberry')); -// Rest parameters. +// 剩余参数 function makeMilkTeaWithRest(flavor: string, sweetness: string = 'full sugar', ...toppings: string[]): string { let tea = `A cup of ${flavor} milk tea with ${sweetness}`; if (toppings.length > 0) { @@ -461,7 +467,7 @@ function makeMilkTeaWithRest(flavor: string, sweetness: string = 'full sugar', . console.log(makeMilkTeaWithRest('strawberry', 'half sugar', 'pearls', 'pudding')); -// Infer return type as string. +// 推断函数返回类型为字符串 function makeMilkTeaWithoutReturnType(flavor: string, sweetness: string) { return `A cup of ${flavor} milk tea with ${sweetness}`; } @@ -479,15 +485,15 @@ function hi2(): void { hi1(); hi2(); -// Function scope. +// 函数作用域 let outerVar = 'I am outer'; function func() { let outerVar = 'I am inside'; - console.log(outerVar); + console.log(outerVar); // 输出:I am inside } -console.log(outerVar); +console.log(outerVar); // 输出:I am outer func(); @Entry diff --git a/entry/src/main/ets/pages/BubbleSortPage.ets b/entry/src/main/ets/pages/BubbleSortPage.ets index adbbd6ff287bc169715d4c234970306e7c32c019..9fb4b02391da848fbdba4c69900b38199bfa3b4a 100644 --- a/entry/src/main/ets/pages/BubbleSortPage.ets +++ b/entry/src/main/ets/pages/BubbleSortPage.ets @@ -12,7 +12,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -// Bubble sort: sort number array in ascending order by swapping adjacent elements. +// 冒泡排序: 通过交换相邻元素,对数字数组进行升序排序。 function BubbleSort(arr: number[]): number[] { const n = arr.length; for (let i = 0; i < n - 1; i++) { diff --git a/entry/src/main/ets/pages/DaffodilsNumberPage.ets b/entry/src/main/ets/pages/DaffodilsNumberPage.ets index 24f35970f53b6528c7d37f1a2e0659fd8047e6c6..65949295ca1b053d719574aa9a8bb3a8ecfc128e 100644 --- a/entry/src/main/ets/pages/DaffodilsNumberPage.ets +++ b/entry/src/main/ets/pages/DaffodilsNumberPage.ets @@ -12,7 +12,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -// Find all 3-digit daffodil numbers. +// 找出所有三位数的水仙花数 function DaffodilsNumber() { let result: number[] = []; for (let i = 100; i < 1000; i++) { diff --git a/entry/src/main/ets/pages/MultiplicationTablePage.ets b/entry/src/main/ets/pages/MultiplicationTablePage.ets index abc64a193e0b9dedd26e70fc42e08bcb399aac59..e67bd2c08ca34df589f4688e21f854f0b69ce173 100644 --- a/entry/src/main/ets/pages/MultiplicationTablePage.ets +++ b/entry/src/main/ets/pages/MultiplicationTablePage.ets @@ -12,7 +12,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -// Print 9x9 multiplication table. +// 打印九九乘法表 function MultiplicationTable() { let result = ''; for (let i = 1; i <= 9; i++) {