diff --git a/AppScope/app.json5 b/AppScope/app.json5 new file mode 100644 index 0000000000000000000000000000000000000000..318905b4571c59d79f558cec8652e99abdee416a --- /dev/null +++ b/AppScope/app.json5 @@ -0,0 +1,10 @@ +{ + "app": { + "bundleName": "com.example.arktsbasicsyntax", + "vendor": "example", + "versionCode": 1000000, + "versionName": "1.0.0", + "icon": "$media:layered_image", + "label": "$string:app_name" + } +} diff --git a/AppScope/resources/base/element/string.json b/AppScope/resources/base/element/string.json new file mode 100644 index 0000000000000000000000000000000000000000..359b13eeed4d7bafd74e1ff19750b679bcd8818e --- /dev/null +++ b/AppScope/resources/base/element/string.json @@ -0,0 +1,8 @@ +{ + "string": [ + { + "name": "app_name", + "value": "ArkTSBasicSyntaxDemo" + } + ] +} diff --git a/AppScope/resources/base/media/background.png b/AppScope/resources/base/media/background.png new file mode 100644 index 0000000000000000000000000000000000000000..923f2b3f27e915d6871871deea0420eb45ce102f Binary files /dev/null and b/AppScope/resources/base/media/background.png differ diff --git a/AppScope/resources/base/media/foreground.png b/AppScope/resources/base/media/foreground.png new file mode 100644 index 0000000000000000000000000000000000000000..eb9427585b36d14b12477435b6419d1f07b3e0bb Binary files /dev/null and b/AppScope/resources/base/media/foreground.png differ diff --git a/AppScope/resources/base/media/layered_image.json b/AppScope/resources/base/media/layered_image.json new file mode 100644 index 0000000000000000000000000000000000000000..fb49920440fb4d246c82f9ada275e26123a2136a --- /dev/null +++ b/AppScope/resources/base/media/layered_image.json @@ -0,0 +1,7 @@ +{ + "layered-image": + { + "background" : "$media:background", + "foreground" : "$media:foreground" + } +} \ No newline at end of file diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..338e5b0bc22082e0ffcc7121c2ed3897a3ddccb0 --- /dev/null +++ b/LICENSE @@ -0,0 +1,78 @@ + Copyright (c) 2024 Huawei Device Co., Ltd. All rights reserved. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +Apache License, Version 2.0 +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + +"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. + +"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. + +"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. + +"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. + +"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. + +"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. + +"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). + +"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. + +"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." + +"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. + +2. Grant of Copyright License. + +Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. + +Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. + +4. Redistribution. + +You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: +1.You must give any other recipients of the Work or Derivative Works a copy of this License; and +2.You must cause any modified files to carry prominent notices stating that You changed the files; and +3.You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and +4.If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. + +You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. + +5. Submission of Contributions. + +Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. + +6. Trademarks. + +This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. + +Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. + +In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. + +While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS \ No newline at end of file diff --git a/README.en.md b/README.en.md deleted file mode 100644 index 57db0ba90f663d1174cf95575909933b1f9d912e..0000000000000000000000000000000000000000 --- a/README.en.md +++ /dev/null @@ -1,36 +0,0 @@ -# ArkTSBasicSyntaxDemo - -#### Description -ArkTS基础语法示例 - -#### Software Architecture -Software architecture description - -#### Installation - -1. xxxx -2. xxxx -3. xxxx - -#### Instructions - -1. xxxx -2. xxxx -3. xxxx - -#### Contribution - -1. Fork the repository -2. Create Feat_xxx branch -3. Commit your code -4. Create Pull Request - - -#### Gitee Feature - -1. You can use Readme\_XXX.md to support different languages, such as Readme\_en.md, Readme\_zh.md -2. Gitee blog [blog.gitee.com](https://blog.gitee.com) -3. Explore open source project [https://gitee.com/explore](https://gitee.com/explore) -4. The most valuable open source project [GVP](https://gitee.com/gvp) -5. The manual of Gitee [https://gitee.com/help](https://gitee.com/help) -6. The most popular members [https://gitee.com/gitee-stars/](https://gitee.com/gitee-stars/) diff --git a/README.md b/README.md index 84e669cacc63e47202a917316c840815d5a18469..e5e9238d01ac0fc52b95a1029f4cca60cb7301c5 100644 --- a/README.md +++ b/README.md @@ -1,37 +1,46 @@ -# ArkTSBasicSyntaxDemo +# ArkTS基础语法示例 -#### 介绍 -ArkTS基础语法示例 +## 介绍 -#### 软件架构 -软件架构说明 +本篇为HarmonyOS第一课《ArkTS基础语法》课程配套Codelab。为初学者介绍ArkTS中的变量声明、类型、语句、函数等核心语法,并实现一些简单的算法。 +## 效果预览 -#### 安装教程 +不涉及 -1. xxxx -2. xxxx -3. xxxx +## 使用说明 -#### 使用说明 +1. 打开BasicPage.ets文件可查看基础语法介绍示例代码,在预览器界面点击刷新,在日志中查看打印结果。 +2. 打开BubbleSortPage.ets文件,在预览器界面点击刷新,在日志中查看冒泡排序结果。 +3. 打开DaffodilsNumberPage.ets文件,在预览器界面点击刷新,在日志中查看三位数水仙花数结果。 +4. 打开MultiplicationTablePage.ets文件,在预览器界面点击刷新,在日志中查看九九乘法表打印结果。 -1. xxxx -2. xxxx -3. xxxx +## 工程目录 -#### 参与贡献 +``` +├──entry/src/main/ets/ +│ ├──entryability +│ │ └──EntryAbility.ets +│ ├──entrybackupability +│ │ └──EntryBackupAbility.ets +│ └──pages +│ ├──BasicPage.ets // 基础语法示例 +│ ├──BubbleSortPage.ets // 冒泡排序 +│ ├──DaffodilsNumberPage.ets // 打印水仙花数 +│ └──MultiplicationTablePage.ets // 打印九九乘法表 +└───entry/src/main/resources // 应用资源目录 +``` -1. Fork 本仓库 -2. 新建 Feat_xxx 分支 -3. 提交代码 -4. 新建 Pull Request +## 相关权限 +不涉及 -#### 特技 +## 约束与限制 -1. 使用 Readme\_XXX.md 来支持不同的语言,例如 Readme\_en.md, Readme\_zh.md -2. Gitee 官方博客 [blog.gitee.com](https://blog.gitee.com) -3. 你可以 [https://gitee.com/explore](https://gitee.com/explore) 这个地址来了解 Gitee 上的优秀开源项目 -4. [GVP](https://gitee.com/gvp) 全称是 Gitee 最有价值开源项目,是综合评定出的优秀开源项目 -5. Gitee 官方提供的使用手册 [https://gitee.com/help](https://gitee.com/help) -6. Gitee 封面人物是一档用来展示 Gitee 会员风采的栏目 [https://gitee.com/gitee-stars/](https://gitee.com/gitee-stars/) +1. 本示例仅支持预览器运行。 + +2. HarmonyOS系统:HarmonyOS 5.0.5 Release及以上。 + +3. DevEco Studio版本:DevEco Studio 6.0.0 Release及以上。 + +4. HarmonyOS SDK版本:HarmonyOS 6.0.0 Release SDK及以上。 diff --git a/build-profile.json5 b/build-profile.json5 new file mode 100644 index 0000000000000000000000000000000000000000..1a6814dc8468417c33947ca74d02b3b3a12db35c --- /dev/null +++ b/build-profile.json5 @@ -0,0 +1,34 @@ +{ + "app": { + "signingConfigs": [], + "products": [ + { + "name": "default", + "signingConfig": "default", + "targetSdkVersion": "6.0.0(20)", + "compatibleSdkVersion": "5.0.5(17)", + "runtimeOS": "HarmonyOS", + "buildOption": { + "strictMode": { + "caseSensitiveCheck": true, + "useNormalizedOHMUrl": true + } + } + } + ], + }, + "modules": [ + { + "name": "entry", + "srcPath": "./entry", + "targets": [ + { + "name": "default", + "applyToProducts": [ + "default" + ] + } + ] + } + ] +} \ No newline at end of file diff --git a/entry/build-profile.json5 b/entry/build-profile.json5 new file mode 100644 index 0000000000000000000000000000000000000000..b23faedd59a8acfcb14f7fda7afcd08500bede8e --- /dev/null +++ b/entry/build-profile.json5 @@ -0,0 +1,9 @@ +{ + "apiType": "stageMode", + "buildOption": {}, + "targets": [ + { + "name": "default" + } + ] +} \ No newline at end of file diff --git a/entry/hvigorfile.ts b/entry/hvigorfile.ts new file mode 100644 index 0000000000000000000000000000000000000000..b0e3a1ab98a91bc918d6404b2413111a5011f14a --- /dev/null +++ b/entry/hvigorfile.ts @@ -0,0 +1,6 @@ +import { hapTasks } from '@ohos/hvigor-ohos-plugin'; + +export default { + system: hapTasks, /* Built-in plugin of Hvigor. It cannot be modified. */ + plugins: [] /* Custom plugin to extend the functionality of Hvigor. */ +} \ No newline at end of file diff --git a/entry/oh-package.json5 b/entry/oh-package.json5 new file mode 100644 index 0000000000000000000000000000000000000000..248c3b7541a589682a250f86a6d3ecf7414d2d6a --- /dev/null +++ b/entry/oh-package.json5 @@ -0,0 +1,10 @@ +{ + "name": "entry", + "version": "1.0.0", + "description": "Please describe the basic information.", + "main": "", + "author": "", + "license": "", + "dependencies": {} +} + diff --git a/entry/src/main/ets/entryability/EntryAbility.ets b/entry/src/main/ets/entryability/EntryAbility.ets new file mode 100644 index 0000000000000000000000000000000000000000..9507fe4e5b57a5b0df7289c6c7f9477141e4b2a0 --- /dev/null +++ b/entry/src/main/ets/entryability/EntryAbility.ets @@ -0,0 +1,62 @@ +/* + * Copyright (c) 2024-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { AbilityConstant, ConfigurationConstant, UIAbility, Want } from '@kit.AbilityKit'; +import { hilog } from '@kit.PerformanceAnalysisKit'; +import { window } from '@kit.ArkUI'; + +const DOMAIN = 0x0000; + +export default class EntryAbility extends UIAbility { + onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void { + try { + this.context.getApplicationContext().setColorMode(ConfigurationConstant.ColorMode.COLOR_MODE_NOT_SET); + } catch (err) { + hilog.error(DOMAIN, 'testTag', 'Failed to set colorMode. Cause: %{public}s', JSON.stringify(err)); + } + hilog.info(DOMAIN, 'testTag', '%{public}s', 'Ability onCreate'); + } + + onDestroy(): void { + hilog.info(DOMAIN, 'testTag', '%{public}s', 'Ability onDestroy'); + } + + onWindowStageCreate(windowStage: window.WindowStage): void { + // Main window is created, set main page for this ability + hilog.info(DOMAIN, 'testTag', '%{public}s', 'Ability onWindowStageCreate'); + + windowStage.loadContent('pages/BasicPage', (err) => { + if (err.code) { + hilog.error(DOMAIN, 'testTag', 'Failed to load the content. Cause: %{public}s', JSON.stringify(err)); + return; + } + hilog.info(DOMAIN, 'testTag', 'Succeeded in loading the content.'); + }); + } + + onWindowStageDestroy(): void { + // Main window is destroyed, release UI related resources + hilog.info(DOMAIN, 'testTag', '%{public}s', 'Ability onWindowStageDestroy'); + } + + onForeground(): void { + // Ability has brought to foreground + hilog.info(DOMAIN, 'testTag', '%{public}s', 'Ability onForeground'); + } + + onBackground(): void { + // Ability has back to background + hilog.info(DOMAIN, 'testTag', '%{public}s', 'Ability onBackground'); + } +} \ No newline at end of file diff --git a/entry/src/main/ets/entrybackupability/EntryBackupAbility.ets b/entry/src/main/ets/entrybackupability/EntryBackupAbility.ets new file mode 100644 index 0000000000000000000000000000000000000000..7a66cd8a8ec9720ea3844781dcd8f67eb9a0b55e --- /dev/null +++ b/entry/src/main/ets/entrybackupability/EntryBackupAbility.ets @@ -0,0 +1,30 @@ +/* + * Copyright (c) 2024-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { hilog } from '@kit.PerformanceAnalysisKit'; +import { BackupExtensionAbility, BundleVersion } from '@kit.CoreFileKit'; + +const DOMAIN = 0x0000; + +export default class EntryBackupAbility extends BackupExtensionAbility { + async onBackup() { + hilog.info(DOMAIN, 'testTag', 'onBackup ok'); + await Promise.resolve(); + } + + async onRestore(bundleVersion: BundleVersion) { + hilog.info(DOMAIN, 'testTag', 'onRestore ok %{public}s', JSON.stringify(bundleVersion)); + await Promise.resolve(); + } +} \ No newline at end of file diff --git a/entry/src/main/ets/pages/BasicPage.ets b/entry/src/main/ets/pages/BasicPage.ets new file mode 100644 index 0000000000000000000000000000000000000000..298a8da663fab5deb336870b95753253a832fc37 --- /dev/null +++ b/entry/src/main/ets/pages/BasicPage.ets @@ -0,0 +1,517 @@ +/* + * Copyright (c) 2024-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * 变量与声明 + */ +function variableDeclaration() { + // 使用let声明变量 + let count: number = 0; + // 后续可重新赋值 + count = 40; + console.log(`count: ${count}`); + + // 使用const声明常量 + const MAX_COUNT: number = 100; + console.log(`MAX_COUNT: ${MAX_COUNT}`); +} + +variableDeclaration(); + +/** + * 类型 + */ +// 基本类型 +function primitiveTypes() { + let a: number = 10; + let b: number = a; + b = 20; + console.log(`a: ${a}`); + console.log(`b: ${b}`); + + // number类型 + let age: number = 20; + let score: number = 90.5; + console.log(`age: ${age}`); + console.log(`score: ${score}`); + + // string类型 + let s1: string = 'Hello!'; // 单引号字符串 + console.log(s1); + + let s2: string = "Hello, world!"; // 双引号字符串 + console.log(s2); + + let result: string = 'Success'; + let s3: string = `The result is ${result}`; // 模版字符串 + console.log(s3); + + // boolean类型 + let isPhoneOn: boolean = true; + let isSunny: boolean = true; + let needUmbrella: boolean = false; + console.log(`Is the phone on: ${isPhoneOn}`); + console.log(`Is it sunny today: ${isSunny}`); + console.log(`Need an umbrella: ${needUmbrella}`); +} + +primitiveTypes(); + +// 引用类型 +function referenceTypes() { + // Object类型 + let o1: Object = 'Alice'; + let o2: Object = ['a', 'b']; + let o3: Object = 1; + console.log(`o1: ${o1}`); + console.log(`o2: ${o2}`); + console.log(`o3: ${o3}`); + + let strObject: String = new String('ArkTS'); + let obj: Object = 'ArkTS'; // 自动装箱为String对象 + let str: string = 'ArkTS'; + console.log(`${str.length}`); // 5 + console.log(`${str.indexOf('T')}`); // 3 + console.log(`strObject: ${strObject}`); + console.log(`obj: ${obj}`); + + // 数组 + let students: string[] = ['XiaoMing', 'XiaoZhang', 'XiaoWang', 'XiaoLi']; // 创建数组 + console.log(students[0]); // 获取索引为0的元素 + students.push('XiaoHong'); + students.pop(); + + let arr1: number[] = [1, 2]; + let arr2: number[] = arr1; + arr2.push(3); + console.log(`arr1: ${arr1}`); + console.log(`arr2: ${arr2}`); +} + +referenceTypes(); + +// 类型系统 +function typeSystem() { + // 声明枚举类型Color,提供Red、Green、Blue三种颜色 + enum Color { + Red, + Green, + Blue + } + + let fontColor: Color = Color.Red; // 直接使用Color.Red进行赋值 + console.log(`fontColor: ${fontColor}`); + + // 联合类型 + let luckNum: number | string = 7; + luckNum = 'seven'; + console.log(`luckNum: ${luckNum}`); + + // 类型别名 + type Matrix = number[][]; // 定义二维数组的别名为Matrix + let arr: Matrix = [[1, 2, 3]]; + console.log(`arr: ${arr}`); + + type NullableObject = Object | null; // 定义可为空的对象的别名为NullableObject + let obj: NullableObject = null; + console.log(`obj: ${JSON.stringify(obj)}`); + + // 类型安全 + let name: string = 'XiaoMing'; + // name = 20; // 类型number不能赋值给类型string + console.log(`name: ${name}`); + + // 类型推断 + let meaningOfLife = 42; // meaningOfLife会被推断为number类型 + console.log(`meaningOfLife: ${meaningOfLife}`); + + // 类型断言 + let anyValue: Object = 'ArkTS'; + let strValue: string = anyValue as string; // 断言为字符串 + console.log(`strValue: ${strValue}`); +} + +typeSystem(); + +/** + * 操作符 + */ +// 赋值运算符 +function assignmentOperators() { + // 基本赋值运算符 + let a = 10; + + // 复合赋值运算符 + a += 5; // 等价于 a = a + 5; + console.log(`a: ${a}`); +} + +assignmentOperators(); + +// 比较运算符 +function compareLoose(a: string | number, b: string | number) { + return a == b; +} + +function compareStrict(a: string | number, b: string | number) { + return a === b; +} + +function comparisonOperators() { + let a: number = 5; + let b: string = '5'; + console.log(`5 == '5': ${compareLoose(a, b)}`); // 5 == '5': true(字符串转为数字) + console.log(`5 === '5': ${compareStrict(a, b)}`); // 5 === '5': false(类型不同) +} + +comparisonOperators(); + +// 算数运算符 +function arithmeticOperators() { + // 一元运算符 + let count = 5; + let result = count++; // 等价于: let result = count; count = count + 1; + console.log(`count: ${count}, result: ${result}`); + + // 二元运算符 + let a = 10; + let b = 4; + console.log(`${a} + ${b} = ${a + b}`); + console.log(`${a} - ${b} = ${a - b}`); + console.log(`${a} * ${b} = ${a * b}`); + console.log(`${a} / ${b} = ${a / b}`); + console.log(`${a} % ${b} = ${a % b}`); +} + +arithmeticOperators(); + +// 逻辑运算符 +function logicalOperators() { + let a = false && true; // false(首个条件为false,直接短路) + let b = true || false; // true(首个条件为true,直接短路) + let c = !false; // true. + console.log(`a: ${a}`); + console.log(`b: ${b}`); + console.log(`c: ${c}`); +} + +logicalOperators(); + +// 位运算符 +function bitwiseOperators() { + let a = 5; + let b = 2; + console.log(`${a} & ${b} = ${a & b}`); + console.log(`${a} | ${b} = ${a | b}`); + console.log(`${a} ^ ${b} = ${a ^ b}`); + console.log(`~ ${a} = ${~a}`); + console.log(`${a} << ${b} = ${a << b}`); + console.log(`${a} >> ${b} = ${a >> b}`); + console.log(`${a} >>> ${b} = ${a >>> b}`); +} + +bitwiseOperators(); + +/** + * 空安全 + */ +function nullSafety() { + // let x: number = null; // 编译时错误 + // let y: string = null; // 编译时错误 + // let z: number[] = null; // 编译时错误 + let x: number | null = null; + x = 1; // ok. + x = null; // ok. + if (x !== null) { + // ... + } +} + +nullSafety(); + +function nullSafetyWithIf(name: string | null) { + if (name !== null) { + // ... + } +} + +nullSafetyWithIf('if'); + +function optionalChaining(name: string | null) { + let len: number | undefined = name?.length; + return len; +} + +optionalChaining('optional chaining'); + +function getLength(name: string | null): number { + // return name.length; // name可能为null + return name!.length; +} + +getLength('non-null assertion operator'); + +function nullSafetyWithNullishCoalescingOperator() { + let name: string | null = null; + const res = name ?? ' '; + console.log(`res: ${res}`); +} + +nullSafetyWithNullishCoalescingOperator(); + +/** + * 语句 + */ +// if语句 +function showIfStatements() { + let hasTicket = true; + if (hasTicket) { + console.log('Ticket verified!'); + } else { + console.log('Entry prohibited!'); + } +} + +showIfStatements(); + +// 条件表达式 +function conditionalExpressions() { + let hasTicket = true; + let result = hasTicket ? 'Ticket verified!' : 'Entry prohibited!'; + console.log(`result: ${result}`); +} + +conditionalExpressions(); + +// switch语句 +function showSwitchStatements() { + let day = 6; + switch (day) { + case 1: + console.log('Monday'); + break; + case 2: + console.log('Tuesday'); + break; + case 3: + console.log('Wednesday'); + break; + case 4: + console.log('Thursday'); + break; + case 5: + console.log('Friday'); + break; + case 6: + case 7: + console.log('Weekend'); + break; + default: + console.log('Invalid input'); + } +} + +showSwitchStatements(); + +// for语句 +function showForStatements() { + let students: string[] = ['XiaoMing', 'XiaoZhang', 'XiaoWang', 'XiaoLi']; + // 通过数组索引访问数组元素 + for (let i = 0; i < students.length; i++) { + console.log(students[i]); // 打印学生信息 + } +} + +showForStatements(); + +// for-of语句 +function showForOfStatements() { + let students: string[] = ['XiaoMing', 'XiaoZhang', 'XiaoWang', 'XiaoLi']; + // 直接获取数组元素 + for (let student of students) { + console.log(student); // 打印学生信息 + } +} + +showForOfStatements(); + +// while语句 +function showWhileStatements() { + let students: string[] = ['XiaoMing', 'XiaoZhang', 'XiaoWang', 'XiaoLi']; + let index = 0; // 初始化索引 + // 循环条件:index小于数组长度 + while (index < students.length) { + console.log(students[index]); // 打印学生信息 + index++; // 索引自增(关键! 否则会无限循环) + } +} + +showWhileStatements(); + +// do-while语句 +function showDoWhileStatements() { + let students: string[] = ['XiaoMing', 'XiaoZhang', 'XiaoWang', 'XiaoLi']; + let index = 0; // 初始化索引 + do { + console.log(students[index]); // 先执行循环体中的语句 + index++; + } while (index < students.length); // 然后判断循环控制表达式 +} + +showDoWhileStatements(); + +// break语句 +function showBreakStatements() { + let students: string[] = ['XiaoMing', 'XiaoZhang', 'XiaoWang', 'XiaoLi']; + for (let i = 0; i < students.length; i++) { + console.log(students[i]); // 打印学生信息 + if (students[i] === 'XiaoWang') { + break; // 终止循环 + } + } + + let x = 1; + label: while (true) { + switch (x) { + case 1: + // ... + break label; // 中断while语句 + } + } +} + +showBreakStatements(); + +// continue语句 +function showContinueStatements() { + let students: string[] = ['XiaoMing', 'XiaoZhang', 'XiaoWang', 'XiaoLi']; + for (let i = 0; i < students.length; i++) { + if (students[i] === 'XiaoWang') { + continue; // 跳出本次循环 + } + console.log(students[i]); // 打印学生信息 + } +} + +showContinueStatements(); + +// throw语句 +function checkAge(age: number) { + if (age < 0) { + throw new Error('Age cannot be negative'); + } +} + +// try语句 +try { + // 可能发生异常的语句 + let result = checkAge(-5); + console.log(`result: ${result}`); +} catch (error) { + // 异常处理 + console.error('Error:', error.message); +} finally { + // 无论是否发生异常都会执行的代码 + console.log('finally'); +} + +/** + * 函数 + */ +// 函数声明 +// 显示指定函数返回类型为字符串 +function makeMilkTea(flavor: string, sweetness: string): string { + return `A cup of ${flavor} milk tea with ${sweetness}`; +} + +let tea = makeMilkTea('strawberry', 'half sugar'); +console.log(tea); +let tea1 = makeMilkTea('passion fruit', 'full sugar'); +console.log(tea1); + +// 可选参数 +function makeMilkTeaWithOptional(flavor: string, sweetness?: string): string { + const sweet = sweetness || 'full sugar'; + return `A cup of ${flavor} milk tea with ${sweet}`; +} + +console.log(makeMilkTeaWithOptional('strawberry')); + +function makeMilkTeaWithOptionalUseDefault(flavor: string, sweetness: string = 'full sugar'): string { + return `A cup of ${flavor} milk tea with ${sweetness}`; +} + +console.log(makeMilkTeaWithOptionalUseDefault('strawberry')); + +// 剩余参数 +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) { + tea += `, add ${toppings.join(', ')}`; + } + return tea; +} + +console.log(makeMilkTeaWithRest('strawberry', 'half sugar', 'pearls', 'pudding')); + +// 推断函数返回类型为字符串 +function makeMilkTeaWithoutReturnType(flavor: string, sweetness: string) { + return `A cup of ${flavor} milk tea with ${sweetness}`; +} + +makeMilkTeaWithoutReturnType('strawberry', 'half sugar'); + +function hi1() { + console.info('hi1'); +} + +function hi2(): void { + console.info('hi2'); +} + +hi1(); +hi2(); + +// 函数作用域 +let outerVar = 'I am outer'; + +function func() { + let outerVar = 'I am inside'; + console.log(outerVar); // 输出:I am inside +} + +console.log(outerVar); // 输出:I am outer +func(); + +@Entry +@Component +struct BasicEnPage { + @State message: string = 'BasicPage'; + + build() { + RelativeContainer() { + Text(this.message) + .id('BubbleSortPageHelloWorld') + .fontSize($r('app.float.page_text_font_size')) + .fontWeight(FontWeight.Bold) + .alignRules({ + center: { anchor: '__container__', align: VerticalAlign.Center }, + middle: { anchor: '__container__', align: HorizontalAlign.Center } + }) + } + .height('100%') + .width('100%') + } +} \ No newline at end of file diff --git a/entry/src/main/ets/pages/BubbleSortPage.ets b/entry/src/main/ets/pages/BubbleSortPage.ets new file mode 100644 index 0000000000000000000000000000000000000000..b56b89a6132fac4a9187475b6fca1897560c1d4a --- /dev/null +++ b/entry/src/main/ets/pages/BubbleSortPage.ets @@ -0,0 +1,53 @@ +/* + * Copyright (c) 2024-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// 冒泡排序: 通过交换相邻元素,对数字数组进行升序排序。 +function BubbleSort(arr: number[]): number[] { + const n = arr.length; + for (let i = 0; i < n - 1; i++) { + for (let j = 0; j < n - 1 - i; j++) { + if (arr[j] > arr[j + 1]) { + const temp = arr[j]; + arr[j] = arr[j + 1]; + arr[j + 1] = temp; + } + } + } + return arr; +} + +let result = BubbleSort([85, 92, 78, 95, 88, 60, 72]); +console.log(`${result}`); + +@Entry +@Component +struct BubbleSortPage { + @State message: string = 'BubbleSortPage'; + + build() { + RelativeContainer() { + Text(this.message) + .id('BubbleSortPage') + .fontSize($r('app.float.page_text_font_size')) + .fontWeight(FontWeight.Bold) + .alignRules({ + center: { anchor: '__container__', align: VerticalAlign.Center }, + middle: { anchor: '__container__', align: HorizontalAlign.Center } + }) + } + .height('100%') + .width('100%') + } +} \ No newline at end of file diff --git a/entry/src/main/ets/pages/DaffodilsNumberPage.ets b/entry/src/main/ets/pages/DaffodilsNumberPage.ets new file mode 100644 index 0000000000000000000000000000000000000000..dd461f7e5e334d12dda309835ad12a16e316713d --- /dev/null +++ b/entry/src/main/ets/pages/DaffodilsNumberPage.ets @@ -0,0 +1,56 @@ +/* + * Copyright (c) 2024-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// 找出所有三位数的水仙花数 +function DaffodilsNumber() { + let result: number[] = []; + for (let i = 100; i < 1000; i++) { + let unitsDigit: number = i % 10; + let tenthsDigit: number = Math.floor(i / 10) % 10; + let hundredthsDigit: number = Math.floor(i / 100); + if (i === unitsDigit * unitsDigit * unitsDigit + tenthsDigit * tenthsDigit * tenthsDigit + + hundredthsDigit * hundredthsDigit * hundredthsDigit) { + result.push(i); + } + } + return result; +} + +let daffodilsNumberResult = DaffodilsNumber(); +console.log(`${daffodilsNumberResult}`); + +@Entry +@Component +struct DaffodilsNumberPage { + @State message: string = 'DaffodilsNumberPage'; + + build() { + RelativeContainer() { + Text(this.message) + .id('DaffodilsNumberPageHelloWorld') + .fontSize($r('app.float.page_text_font_size')) + .fontWeight(FontWeight.Bold) + .alignRules({ + center: { anchor: '__container__', align: VerticalAlign.Center }, + middle: { anchor: '__container__', align: HorizontalAlign.Center } + }) + .onClick(() => { + this.message = 'Welcome'; + }) + } + .height('100%') + .width('100%') + } +} \ No newline at end of file diff --git a/entry/src/main/ets/pages/MultiplicationTablePage.ets b/entry/src/main/ets/pages/MultiplicationTablePage.ets new file mode 100644 index 0000000000000000000000000000000000000000..1567b5a6197038e055862d495efc1cac129c816e --- /dev/null +++ b/entry/src/main/ets/pages/MultiplicationTablePage.ets @@ -0,0 +1,51 @@ +/* + * Copyright (c) 2024-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// 打印九九乘法表 +function MultiplicationTable() { + let result = ''; + for (let i = 1; i <= 9; i++) { + for (let j = 1; j <= i; j++) { + let temp: string = j + ' * ' + i + ' = ' + i * j; + result += temp; + result += ' '; + } + console.log(result); + result = ''; + } +} + +MultiplicationTable(); + +@Entry +@Component +struct MultiplicationTablePage { + @State message: string = 'MultiplicationTablePage'; + + build() { + RelativeContainer() { + Text(this.message) + .id('MultiplicationTablePageHelloWorld') + .fontSize($r('app.float.page_text_font_size')) + .fontWeight(FontWeight.Bold) + .alignRules({ + center: { anchor: '__container__', align: VerticalAlign.Center }, + middle: { anchor: '__container__', align: HorizontalAlign.Center } + }) + } + .height('100%') + .width('100%') + } +} \ No newline at end of file diff --git a/entry/src/main/module.json5 b/entry/src/main/module.json5 new file mode 100644 index 0000000000000000000000000000000000000000..53024e8f020cc0824592631ba6924108c8028f0f --- /dev/null +++ b/entry/src/main/module.json5 @@ -0,0 +1,50 @@ +{ + "module": { + "name": "entry", + "type": "entry", + "description": "$string:module_desc", + "mainElement": "EntryAbility", + "deviceTypes": [ + "phone" + ], + "deliveryWithInstall": true, + "installationFree": false, + "pages": "$profile:main_pages", + "abilities": [ + { + "name": "EntryAbility", + "srcEntry": "./ets/entryability/EntryAbility.ets", + "description": "$string:EntryAbility_desc", + "icon": "$media:layered_image", + "label": "$string:EntryAbility_label", + "startWindowIcon": "$media:startIcon", + "startWindowBackground": "$color:start_window_background", + "exported": true, + "skills": [ + { + "entities": [ + "entity.system.home" + ], + "actions": [ + "ohos.want.action.home" + ] + } + ] + } + ], + "extensionAbilities": [ + { + "name": "EntryBackupAbility", + "srcEntry": "./ets/entrybackupability/EntryBackupAbility.ets", + "type": "backup", + "exported": false, + "metadata": [ + { + "name": "ohos.extension.backup", + "resource": "$profile:backup_config" + } + ], + } + ] + } +} \ No newline at end of file diff --git a/entry/src/main/resources/base/element/color.json b/entry/src/main/resources/base/element/color.json new file mode 100644 index 0000000000000000000000000000000000000000..3c712962da3c2751c2b9ddb53559afcbd2b54a02 --- /dev/null +++ b/entry/src/main/resources/base/element/color.json @@ -0,0 +1,8 @@ +{ + "color": [ + { + "name": "start_window_background", + "value": "#FFFFFF" + } + ] +} \ No newline at end of file diff --git a/entry/src/main/resources/base/element/float.json b/entry/src/main/resources/base/element/float.json new file mode 100644 index 0000000000000000000000000000000000000000..b7842d22324d3135d55fc8d0e6175fa28ad2a32b --- /dev/null +++ b/entry/src/main/resources/base/element/float.json @@ -0,0 +1,8 @@ +{ + "float": [ + { + "name": "page_text_font_size", + "value": "30fp" + } + ] +} \ No newline at end of file diff --git a/entry/src/main/resources/base/element/string.json b/entry/src/main/resources/base/element/string.json new file mode 100644 index 0000000000000000000000000000000000000000..82fa203fec0e6146b1a4bff2d087ca41448fe28c --- /dev/null +++ b/entry/src/main/resources/base/element/string.json @@ -0,0 +1,16 @@ +{ + "string": [ + { + "name": "module_desc", + "value": "module description" + }, + { + "name": "EntryAbility_desc", + "value": "description" + }, + { + "name": "EntryAbility_label", + "value": "ArkTSBasicSyntaxDemo" + } + ] +} \ No newline at end of file diff --git a/entry/src/main/resources/base/media/background.png b/entry/src/main/resources/base/media/background.png new file mode 100644 index 0000000000000000000000000000000000000000..923f2b3f27e915d6871871deea0420eb45ce102f Binary files /dev/null and b/entry/src/main/resources/base/media/background.png differ diff --git a/entry/src/main/resources/base/media/foreground.png b/entry/src/main/resources/base/media/foreground.png new file mode 100644 index 0000000000000000000000000000000000000000..97014d3e10e5ff511409c378cd4255713aecd85f Binary files /dev/null and b/entry/src/main/resources/base/media/foreground.png differ diff --git a/entry/src/main/resources/base/media/layered_image.json b/entry/src/main/resources/base/media/layered_image.json new file mode 100644 index 0000000000000000000000000000000000000000..fb49920440fb4d246c82f9ada275e26123a2136a --- /dev/null +++ b/entry/src/main/resources/base/media/layered_image.json @@ -0,0 +1,7 @@ +{ + "layered-image": + { + "background" : "$media:background", + "foreground" : "$media:foreground" + } +} \ No newline at end of file diff --git a/entry/src/main/resources/base/media/startIcon.png b/entry/src/main/resources/base/media/startIcon.png new file mode 100644 index 0000000000000000000000000000000000000000..205ad8b5a8a42e8762fbe4899b8e5e31ce822b8b Binary files /dev/null and b/entry/src/main/resources/base/media/startIcon.png differ diff --git a/entry/src/main/resources/base/profile/backup_config.json b/entry/src/main/resources/base/profile/backup_config.json new file mode 100644 index 0000000000000000000000000000000000000000..78f40ae7c494d71e2482278f359ec790ca73471a --- /dev/null +++ b/entry/src/main/resources/base/profile/backup_config.json @@ -0,0 +1,3 @@ +{ + "allowToBackupRestore": true +} \ No newline at end of file diff --git a/entry/src/main/resources/base/profile/main_pages.json b/entry/src/main/resources/base/profile/main_pages.json new file mode 100644 index 0000000000000000000000000000000000000000..7864effd11bf92ee27cde3025674461e26be84e0 --- /dev/null +++ b/entry/src/main/resources/base/profile/main_pages.json @@ -0,0 +1,8 @@ +{ + "src": [ + "pages/BasicPage", + "pages/BubbleSortPage", + "pages/DaffodilsNumberPage", + "pages/MultiplicationTablePage" + ] +} \ No newline at end of file diff --git a/entry/src/main/resources/dark/element/color.json b/entry/src/main/resources/dark/element/color.json new file mode 100644 index 0000000000000000000000000000000000000000..79b11c2747aec33e710fd3a7b2b3c94dd9965499 --- /dev/null +++ b/entry/src/main/resources/dark/element/color.json @@ -0,0 +1,8 @@ +{ + "color": [ + { + "name": "start_window_background", + "value": "#000000" + } + ] +} \ No newline at end of file diff --git a/hvigor/hvigor-config.json5 b/hvigor/hvigor-config.json5 new file mode 100644 index 0000000000000000000000000000000000000000..7a7ab8914d8db6ab89758e185df5855dffe88d04 --- /dev/null +++ b/hvigor/hvigor-config.json5 @@ -0,0 +1,23 @@ +{ + "modelVersion": "6.0.0", + "dependencies": { + }, + "execution": { + // "analyze": "normal", /* Define the build analyze mode. Value: [ "normal" | "advanced" | "ultrafine" | false ]. Default: "normal" */ + // "daemon": true, /* Enable daemon compilation. Value: [ true | false ]. Default: true */ + // "incremental": true, /* Enable incremental compilation. Value: [ true | false ]. Default: true */ + // "parallel": true, /* Enable parallel compilation. Value: [ true | false ]. Default: true */ + // "typeCheck": false, /* Enable typeCheck. Value: [ true | false ]. Default: false */ + // "optimizationStrategy": "memory" /* Define the optimization strategy. Value: [ "memory" | "performance" ]. Default: "memory" */ + }, + "logging": { + // "level": "info" /* Define the log level. Value: [ "debug" | "info" | "warn" | "error" ]. Default: "info" */ + }, + "debugging": { + // "stacktrace": false /* Disable stacktrace compilation. Value: [ true | false ]. Default: false */ + }, + "nodeOptions": { + // "maxOldSpaceSize": 8192 /* Enable nodeOptions maxOldSpaceSize compilation. Unit M. Used for the daemon process. Default: 8192*/ + // "exposeGC": true /* Enable to trigger garbage collection explicitly. Default: true*/ + } +} diff --git a/hvigorfile.ts b/hvigorfile.ts new file mode 100644 index 0000000000000000000000000000000000000000..47113e2e36ecefde41c136272a0bd6ff745cffe4 --- /dev/null +++ b/hvigorfile.ts @@ -0,0 +1,6 @@ +import { appTasks } from '@ohos/hvigor-ohos-plugin'; + +export default { + system: appTasks, /* Built-in plugin of Hvigor. It cannot be modified. */ + plugins: [] /* Custom plugin to extend the functionality of Hvigor. */ +} \ No newline at end of file diff --git a/oh-package.json5 b/oh-package.json5 new file mode 100644 index 0000000000000000000000000000000000000000..96463c34a1d8fb87fe2b01d9e47f510104e035cc --- /dev/null +++ b/oh-package.json5 @@ -0,0 +1,7 @@ +{ + "modelVersion": "6.0.0", + "description": "Please describe the basic information.", + "dependencies": { + }, + "devDependencies": {} +}