@lppx/nlearn 1.1.12 → 1.1.13
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/src/demo/operators-expressions/01-/345/237/272/347/241/200/350/277/220/347/256/227/347/254/246.js +144 -0
- package/dist/src/demo/operators-expressions/02-/347/261/273/345/236/213/350/277/220/347/256/227/347/254/246.js +212 -0
- package/dist/src/demo/operators-expressions/03-/344/275/215/350/277/220/347/256/227/347/254/246.js +190 -0
- package/dist/src/demo/operators-expressions/04-/350/241/250/350/276/276/345/274/217/344/270/216/346/261/202/345/200/274.js +202 -0
- package/package.json +1 -1
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* TypeScript 基础运算符
|
|
4
|
+
* =====================
|
|
5
|
+
* 涵盖算术运算符、赋值运算符、比较运算符和逻辑运算符
|
|
6
|
+
* 适用于 TypeScript 5.x
|
|
7
|
+
*/
|
|
8
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
9
|
+
exports.arithmeticOperators = arithmeticOperators;
|
|
10
|
+
exports.assignmentOperators = assignmentOperators;
|
|
11
|
+
exports.comparisonOperators = comparisonOperators;
|
|
12
|
+
exports.logicalOperators = logicalOperators;
|
|
13
|
+
exports.stringOperators = stringOperators;
|
|
14
|
+
// #region 示例1: 算术运算符
|
|
15
|
+
function arithmeticOperators() {
|
|
16
|
+
console.log('=== 算术运算符 ===');
|
|
17
|
+
const a = 10;
|
|
18
|
+
const b = 3;
|
|
19
|
+
console.log(`加法: ${a} + ${b} = ${a + b}`);
|
|
20
|
+
console.log(`减法: ${a} - ${b} = ${a - b}`);
|
|
21
|
+
console.log(`乘法: ${a} * ${b} = ${a * b}`);
|
|
22
|
+
console.log(`除法: ${a} / ${b} = ${a / b}`);
|
|
23
|
+
console.log(`取余: ${a} % ${b} = ${a % b}`);
|
|
24
|
+
console.log(`幂运算: ${a} ** ${b} = ${a ** b}`);
|
|
25
|
+
// 自增自减
|
|
26
|
+
let count = 5;
|
|
27
|
+
console.log(`\n原始值: ${count}`);
|
|
28
|
+
console.log(`后置自增 count++: ${count++}`); // 先返回再加
|
|
29
|
+
console.log(`自增后的值: ${count}`);
|
|
30
|
+
console.log(`前置自增 ++count: ${++count}`); // 先加再返回
|
|
31
|
+
console.log(`后置自减 count--: ${count--}`);
|
|
32
|
+
console.log(`前置自减 --count: ${--count}`);
|
|
33
|
+
}
|
|
34
|
+
// #endregion
|
|
35
|
+
// #region 示例2: 赋值运算符
|
|
36
|
+
function assignmentOperators() {
|
|
37
|
+
console.log('\n=== 赋值运算符 ===');
|
|
38
|
+
let x = 10;
|
|
39
|
+
console.log(`初始值: x = ${x}`);
|
|
40
|
+
x += 5; // x = x + 5
|
|
41
|
+
console.log(`x += 5: ${x}`);
|
|
42
|
+
x -= 3; // x = x - 3
|
|
43
|
+
console.log(`x -= 3: ${x}`);
|
|
44
|
+
x *= 2; // x = x * 2
|
|
45
|
+
console.log(`x *= 2: ${x}`);
|
|
46
|
+
x /= 4; // x = x / 4
|
|
47
|
+
console.log(`x /= 4: ${x}`);
|
|
48
|
+
x %= 5; // x = x % 5
|
|
49
|
+
console.log(`x %= 5: ${x}`);
|
|
50
|
+
x **= 3; // x = x ** 3
|
|
51
|
+
console.log(`x **= 3: ${x}`);
|
|
52
|
+
}
|
|
53
|
+
// #endregion
|
|
54
|
+
// #region 示例3: 比较运算符
|
|
55
|
+
function comparisonOperators() {
|
|
56
|
+
console.log('\n=== 比较运算符 ===');
|
|
57
|
+
const num1 = 10;
|
|
58
|
+
const num2 = '10'; // 使用 any 来演示类型转换
|
|
59
|
+
const num3 = 20;
|
|
60
|
+
// 相等性比较
|
|
61
|
+
console.log(`${num1} == '${num2}': ${num1 == num2}`); // 宽松相等(类型转换)
|
|
62
|
+
console.log(`${num1} === '${num2}': ${num1 === num2}`); // 严格相等(不转换类型)
|
|
63
|
+
console.log(`${num1} != '${num2}': ${num1 != num2}`);
|
|
64
|
+
console.log(`${num1} !== '${num2}': ${num1 !== num2}`);
|
|
65
|
+
// 大小比较
|
|
66
|
+
console.log(`\n${num1} > ${num3}: ${num1 > num3}`);
|
|
67
|
+
console.log(`${num1} < ${num3}: ${num1 < num3}`);
|
|
68
|
+
console.log(`${num1} >= ${num1}: ${num1 >= num1}`);
|
|
69
|
+
console.log(`${num1} <= ${num3}: ${num1 <= num3}`);
|
|
70
|
+
}
|
|
71
|
+
// #endregion
|
|
72
|
+
// #region 示例4: 逻辑运算符
|
|
73
|
+
function logicalOperators() {
|
|
74
|
+
console.log('\n=== 逻辑运算符 ===');
|
|
75
|
+
const isAdult = true;
|
|
76
|
+
const hasLicense = false;
|
|
77
|
+
const age = 25;
|
|
78
|
+
// 逻辑与 (AND)
|
|
79
|
+
console.log(`isAdult && hasLicense: ${isAdult && hasLicense}`);
|
|
80
|
+
console.log(`可以开车: ${isAdult && hasLicense}`);
|
|
81
|
+
// 逻辑或 (OR)
|
|
82
|
+
console.log(`\nisAdult || hasLicense: ${isAdult || hasLicense}`);
|
|
83
|
+
console.log(`至少满足一个条件: ${isAdult || hasLicense}`);
|
|
84
|
+
// 逻辑非 (NOT)
|
|
85
|
+
console.log(`\n!isAdult: ${!isAdult}`);
|
|
86
|
+
console.log(`!hasLicense: ${!hasLicense}`);
|
|
87
|
+
// 组合使用
|
|
88
|
+
const canDrive = isAdult && hasLicense;
|
|
89
|
+
const needsPermission = !isAdult || !hasLicense;
|
|
90
|
+
console.log(`\n可以开车: ${canDrive}`);
|
|
91
|
+
console.log(`需要许可: ${needsPermission}`);
|
|
92
|
+
// 短路求值
|
|
93
|
+
console.log('\n短路求值示例:');
|
|
94
|
+
const result1 = false && console.log('这不会执行');
|
|
95
|
+
const result2 = true || console.log('这也不会执行');
|
|
96
|
+
console.log('短路求值完成');
|
|
97
|
+
}
|
|
98
|
+
// #endregion
|
|
99
|
+
// #region 示例5: 字符串运算符
|
|
100
|
+
function stringOperators() {
|
|
101
|
+
console.log('\n=== 字符串运算符 ===');
|
|
102
|
+
const firstName = 'Zhang';
|
|
103
|
+
const lastName = 'San';
|
|
104
|
+
// 字符串连接
|
|
105
|
+
const fullName = firstName + ' ' + lastName;
|
|
106
|
+
console.log(`全名: ${fullName}`);
|
|
107
|
+
// 使用 += 连接
|
|
108
|
+
let message = 'Hello';
|
|
109
|
+
message += ', ';
|
|
110
|
+
message += 'World!';
|
|
111
|
+
console.log(`消息: ${message}`);
|
|
112
|
+
// 模板字符串(推荐方式)
|
|
113
|
+
const greeting = `你好, ${firstName} ${lastName}!`;
|
|
114
|
+
console.log(greeting);
|
|
115
|
+
// 字符串与数字
|
|
116
|
+
const str = '100'; // 使用 any 来演示类型转换
|
|
117
|
+
const num = 50;
|
|
118
|
+
console.log(`\n字符串 + 数字: '${str}' + ${num} = ${str + num}`); // 字符串连接
|
|
119
|
+
console.log(`字符串 - 数字: '${str}' - ${num} = ${str - num}`); // 数字运算(自动转换)
|
|
120
|
+
}
|
|
121
|
+
// #endregion
|
|
122
|
+
if (require.main === module) {
|
|
123
|
+
const examples = [
|
|
124
|
+
arithmeticOperators,
|
|
125
|
+
assignmentOperators,
|
|
126
|
+
comparisonOperators,
|
|
127
|
+
logicalOperators,
|
|
128
|
+
stringOperators
|
|
129
|
+
];
|
|
130
|
+
const exampleNumber = parseInt(process.argv[2]);
|
|
131
|
+
if (exampleNumber && exampleNumber > 0 && exampleNumber <= examples.length) {
|
|
132
|
+
console.log(`\n运行示例 ${exampleNumber}:\n`);
|
|
133
|
+
examples[exampleNumber - 1]();
|
|
134
|
+
}
|
|
135
|
+
else {
|
|
136
|
+
console.log('运行所有示例:\n');
|
|
137
|
+
examples.forEach((example, index) => {
|
|
138
|
+
console.log(`\n${'='.repeat(50)}`);
|
|
139
|
+
console.log(`示例 ${index + 1}`);
|
|
140
|
+
console.log('='.repeat(50));
|
|
141
|
+
example();
|
|
142
|
+
});
|
|
143
|
+
}
|
|
144
|
+
}
|
|
@@ -0,0 +1,212 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* TypeScript 类型运算符
|
|
4
|
+
* =====================
|
|
5
|
+
* 涵盖 typeof、instanceof、in、as 等类型相关运算符
|
|
6
|
+
* 适用于 TypeScript 5.x
|
|
7
|
+
*/
|
|
8
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
9
|
+
exports.typeofOperator = typeofOperator;
|
|
10
|
+
exports.instanceofOperator = instanceofOperator;
|
|
11
|
+
exports.inOperator = inOperator;
|
|
12
|
+
exports.typeAssertion = typeAssertion;
|
|
13
|
+
exports.optionalChainingAndNullish = optionalChainingAndNullish;
|
|
14
|
+
// #region 示例1: typeof 运算符
|
|
15
|
+
function typeofOperator() {
|
|
16
|
+
console.log('=== typeof 运算符 ===');
|
|
17
|
+
// 基本类型检测
|
|
18
|
+
console.log(`typeof 42: ${typeof 42}`);
|
|
19
|
+
console.log(`typeof 'hello': ${typeof 'hello'}`);
|
|
20
|
+
console.log(`typeof true: ${typeof true}`);
|
|
21
|
+
console.log(`typeof undefined: ${typeof undefined}`);
|
|
22
|
+
console.log(`typeof null: ${typeof null}`); // 注意:这是 JavaScript 的历史遗留问题
|
|
23
|
+
console.log(`typeof Symbol(): ${typeof Symbol()}`);
|
|
24
|
+
console.log(`typeof 123n: ${typeof 123n}`);
|
|
25
|
+
// 复杂类型
|
|
26
|
+
console.log(`\ntypeof {}: ${typeof {}}`);
|
|
27
|
+
console.log(`typeof []: ${typeof []}`);
|
|
28
|
+
console.log(`typeof function(){}: ${typeof function () { }}`);
|
|
29
|
+
// 实际应用
|
|
30
|
+
function processValue(value) {
|
|
31
|
+
if (typeof value === 'string') {
|
|
32
|
+
console.log(`\n字符串长度: ${value.length}`);
|
|
33
|
+
}
|
|
34
|
+
else if (typeof value === 'number') {
|
|
35
|
+
console.log(`\n数字平方: ${value ** 2}`);
|
|
36
|
+
}
|
|
37
|
+
else {
|
|
38
|
+
console.log(`\n未知类型: ${typeof value}`);
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
processValue('TypeScript');
|
|
42
|
+
processValue(10);
|
|
43
|
+
processValue(true);
|
|
44
|
+
}
|
|
45
|
+
// #endregion
|
|
46
|
+
// #region 示例2: instanceof 运算符
|
|
47
|
+
class Animal {
|
|
48
|
+
constructor(name) {
|
|
49
|
+
this.name = name;
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
class Dog extends Animal {
|
|
53
|
+
bark() {
|
|
54
|
+
return `${this.name} says: Woof!`;
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
class Cat extends Animal {
|
|
58
|
+
meow() {
|
|
59
|
+
return `${this.name} says: Meow!`;
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
function instanceofOperator() {
|
|
63
|
+
console.log('\n=== instanceof 运算符 ===');
|
|
64
|
+
const dog = new Dog('旺财');
|
|
65
|
+
const cat = new Cat('咪咪');
|
|
66
|
+
const date = new Date();
|
|
67
|
+
const arr = [1, 2, 3];
|
|
68
|
+
// 类实例检测
|
|
69
|
+
console.log(`dog instanceof Dog: ${dog instanceof Dog}`);
|
|
70
|
+
console.log(`dog instanceof Animal: ${dog instanceof Animal}`);
|
|
71
|
+
console.log(`cat instanceof Dog: ${cat instanceof Dog}`);
|
|
72
|
+
// 内置对象检测
|
|
73
|
+
console.log(`\ndate instanceof Date: ${date instanceof Date}`);
|
|
74
|
+
console.log(`arr instanceof Array: ${arr instanceof Array}`);
|
|
75
|
+
console.log(`arr instanceof Object: ${arr instanceof Object}`);
|
|
76
|
+
// 实际应用:类型守卫
|
|
77
|
+
function handleAnimal(animal) {
|
|
78
|
+
if (animal instanceof Dog) {
|
|
79
|
+
console.log(`\n${animal.bark()}`);
|
|
80
|
+
}
|
|
81
|
+
else if (animal instanceof Cat) {
|
|
82
|
+
console.log(`\n${animal.meow()}`);
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
handleAnimal(dog);
|
|
86
|
+
handleAnimal(cat);
|
|
87
|
+
}
|
|
88
|
+
function inOperator() {
|
|
89
|
+
console.log('\n=== in 运算符 ===');
|
|
90
|
+
const user = {
|
|
91
|
+
name: '张三',
|
|
92
|
+
email: 'zhangsan@example.com'
|
|
93
|
+
};
|
|
94
|
+
const admin = {
|
|
95
|
+
name: '李四',
|
|
96
|
+
email: 'lisi@example.com',
|
|
97
|
+
role: 'admin',
|
|
98
|
+
permissions: ['read', 'write', 'delete']
|
|
99
|
+
};
|
|
100
|
+
// 检查属性是否存在
|
|
101
|
+
console.log(`'name' in user: ${'name' in user}`);
|
|
102
|
+
console.log(`'role' in user: ${'role' in user}`);
|
|
103
|
+
console.log(`'role' in admin: ${'role' in admin}`);
|
|
104
|
+
// 检查数组索引
|
|
105
|
+
const arr = [1, 2, 3];
|
|
106
|
+
console.log(`\n0 in arr: ${0 in arr}`);
|
|
107
|
+
console.log(`5 in arr: ${5 in arr}`);
|
|
108
|
+
console.log(`'length' in arr: ${'length' in arr}`);
|
|
109
|
+
// 实际应用:类型守卫
|
|
110
|
+
function printUserInfo(user) {
|
|
111
|
+
console.log(`\n姓名: ${user.name}`);
|
|
112
|
+
console.log(`邮箱: ${user.email}`);
|
|
113
|
+
if ('role' in user) {
|
|
114
|
+
console.log(`角色: ${user.role}`);
|
|
115
|
+
console.log(`权限: ${user.permissions.join(', ')}`);
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
printUserInfo(user);
|
|
119
|
+
printUserInfo(admin);
|
|
120
|
+
}
|
|
121
|
+
// #endregion
|
|
122
|
+
// #region 示例4: 类型断言 (as)
|
|
123
|
+
function typeAssertion() {
|
|
124
|
+
console.log('\n=== 类型断言 (as) ===');
|
|
125
|
+
// 基本类型断言
|
|
126
|
+
const someValue = 'this is a string';
|
|
127
|
+
const strLength = someValue.length;
|
|
128
|
+
console.log(`字符串长度: ${strLength}`);
|
|
129
|
+
// 模拟 DOM 元素
|
|
130
|
+
const element = { value: 'Hello' };
|
|
131
|
+
const inputElement = element;
|
|
132
|
+
console.log(`输入值: ${inputElement.value}`);
|
|
133
|
+
function handleResponse(response) {
|
|
134
|
+
if (response.success) {
|
|
135
|
+
const data = response.data;
|
|
136
|
+
console.log(`\n成功: ${data}`);
|
|
137
|
+
}
|
|
138
|
+
else {
|
|
139
|
+
const error = response.error;
|
|
140
|
+
console.log(`\n失败: ${error}`);
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
handleResponse({ success: true, data: '操作成功' });
|
|
144
|
+
handleResponse({ success: false, error: '网络错误' });
|
|
145
|
+
// 非空断言 (!)
|
|
146
|
+
function processString(str) {
|
|
147
|
+
// 当我们确定 str 不为 null 时使用
|
|
148
|
+
const length = str.length;
|
|
149
|
+
return length;
|
|
150
|
+
}
|
|
151
|
+
console.log(`\n非空断言示例: ${processString('TypeScript')}`);
|
|
152
|
+
}
|
|
153
|
+
// #endregion
|
|
154
|
+
// #region 示例5: 可选链和空值合并
|
|
155
|
+
function optionalChainingAndNullish() {
|
|
156
|
+
console.log('\n=== 可选链 (?.) 和空值合并 (??) ===');
|
|
157
|
+
const person1 = {
|
|
158
|
+
name: '张三',
|
|
159
|
+
address: {
|
|
160
|
+
city: '北京',
|
|
161
|
+
zipCode: '100000'
|
|
162
|
+
}
|
|
163
|
+
};
|
|
164
|
+
const person2 = {
|
|
165
|
+
name: '李四'
|
|
166
|
+
};
|
|
167
|
+
// 可选链操作符
|
|
168
|
+
console.log(`person1 城市: ${person1.address?.city}`);
|
|
169
|
+
console.log(`person1 街道: ${person1.address?.street}`);
|
|
170
|
+
console.log(`person2 城市: ${person2.address?.city}`);
|
|
171
|
+
// 空值合并操作符
|
|
172
|
+
const phone1 = person1.phone ?? '未提供';
|
|
173
|
+
const phone2 = person2.phone ?? '未提供';
|
|
174
|
+
console.log(`\nperson1 电话: ${phone1}`);
|
|
175
|
+
console.log(`person2 电话: ${phone2}`);
|
|
176
|
+
// 与逻辑或的区别
|
|
177
|
+
const value1 = 0;
|
|
178
|
+
const value2 = '';
|
|
179
|
+
const value3 = null;
|
|
180
|
+
console.log(`\n0 || 'default': ${value1 || 'default'}`);
|
|
181
|
+
console.log(`0 ?? 'default': ${value1 ?? 'default'}`);
|
|
182
|
+
console.log(`'' || 'default': ${value2 || 'default'}`);
|
|
183
|
+
console.log(`'' ?? 'default': ${value2 ?? 'default'}`);
|
|
184
|
+
console.log(`null ?? 'default': ${value3 ?? 'default'}`);
|
|
185
|
+
// 组合使用
|
|
186
|
+
const city = person2.address?.city ?? '未知城市';
|
|
187
|
+
console.log(`\nperson2 城市(带默认值): ${city}`);
|
|
188
|
+
}
|
|
189
|
+
// #endregion
|
|
190
|
+
if (require.main === module) {
|
|
191
|
+
const examples = [
|
|
192
|
+
typeofOperator,
|
|
193
|
+
instanceofOperator,
|
|
194
|
+
inOperator,
|
|
195
|
+
typeAssertion,
|
|
196
|
+
optionalChainingAndNullish
|
|
197
|
+
];
|
|
198
|
+
const exampleNumber = parseInt(process.argv[2]);
|
|
199
|
+
if (exampleNumber && exampleNumber > 0 && exampleNumber <= examples.length) {
|
|
200
|
+
console.log(`\n运行示例 ${exampleNumber}:\n`);
|
|
201
|
+
examples[exampleNumber - 1]();
|
|
202
|
+
}
|
|
203
|
+
else {
|
|
204
|
+
console.log('运行所有示例:\n');
|
|
205
|
+
examples.forEach((example, index) => {
|
|
206
|
+
console.log(`\n${'='.repeat(50)}`);
|
|
207
|
+
console.log(`示例 ${index + 1}`);
|
|
208
|
+
console.log('='.repeat(50));
|
|
209
|
+
example();
|
|
210
|
+
});
|
|
211
|
+
}
|
|
212
|
+
}
|
package/dist/src/demo/operators-expressions/03-/344/275/215/350/277/220/347/256/227/347/254/246.js
ADDED
|
@@ -0,0 +1,190 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* TypeScript 位运算符
|
|
4
|
+
* ===================
|
|
5
|
+
* 涵盖位与、位或、位异或、位非、左移、右移等位运算操作
|
|
6
|
+
* 适用于 TypeScript 5.x
|
|
7
|
+
*/
|
|
8
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
9
|
+
exports.basicBitwiseOperators = basicBitwiseOperators;
|
|
10
|
+
exports.shiftOperators = shiftOperators;
|
|
11
|
+
exports.permissionSystem = permissionSystem;
|
|
12
|
+
exports.colorProcessing = colorProcessing;
|
|
13
|
+
exports.bitwiseTricks = bitwiseTricks;
|
|
14
|
+
// #region 示例1: 基础位运算符
|
|
15
|
+
function basicBitwiseOperators() {
|
|
16
|
+
console.log('=== 基础位运算符 ===');
|
|
17
|
+
const a = 5; // 二进制: 0101
|
|
18
|
+
const b = 3; // 二进制: 0011
|
|
19
|
+
console.log(`a = ${a} (二进制: ${a.toString(2).padStart(4, '0')})`);
|
|
20
|
+
console.log(`b = ${b} (二进制: ${b.toString(2).padStart(4, '0')})`);
|
|
21
|
+
// 位与 (AND)
|
|
22
|
+
const and = a & b; // 0101 & 0011 = 0001
|
|
23
|
+
console.log(`\na & b = ${and} (二进制: ${and.toString(2).padStart(4, '0')})`);
|
|
24
|
+
// 位或 (OR)
|
|
25
|
+
const or = a | b; // 0101 | 0011 = 0111
|
|
26
|
+
console.log(`a | b = ${or} (二进制: ${or.toString(2).padStart(4, '0')})`);
|
|
27
|
+
// 位异或 (XOR)
|
|
28
|
+
const xor = a ^ b; // 0101 ^ 0011 = 0110
|
|
29
|
+
console.log(`a ^ b = ${xor} (二进制: ${xor.toString(2).padStart(4, '0')})`);
|
|
30
|
+
// 位非 (NOT)
|
|
31
|
+
const notA = ~a; // ~0101 = ...11111010 (补码表示)
|
|
32
|
+
console.log(`~a = ${notA}`);
|
|
33
|
+
}
|
|
34
|
+
// #endregion
|
|
35
|
+
// #region 示例2: 移位运算符
|
|
36
|
+
function shiftOperators() {
|
|
37
|
+
console.log('\n=== 移位运算符 ===');
|
|
38
|
+
const num = 8; // 二进制: 1000
|
|
39
|
+
console.log(`原始值: ${num} (二进制: ${num.toString(2)})`);
|
|
40
|
+
// 左移 (<<)
|
|
41
|
+
const leftShift1 = num << 1; // 1000 << 1 = 10000 (16)
|
|
42
|
+
const leftShift2 = num << 2; // 1000 << 2 = 100000 (32)
|
|
43
|
+
console.log(`\n${num} << 1 = ${leftShift1} (相当于乘以 2)`);
|
|
44
|
+
console.log(`${num} << 2 = ${leftShift2} (相当于乘以 4)`);
|
|
45
|
+
// 右移 (>>)
|
|
46
|
+
const rightShift1 = num >> 1; // 1000 >> 1 = 0100 (4)
|
|
47
|
+
const rightShift2 = num >> 2; // 1000 >> 2 = 0010 (2)
|
|
48
|
+
console.log(`\n${num} >> 1 = ${rightShift1} (相当于除以 2)`);
|
|
49
|
+
console.log(`${num} >> 2 = ${rightShift2} (相当于除以 4)`);
|
|
50
|
+
// 无符号右移 (>>>)
|
|
51
|
+
const negNum = -8;
|
|
52
|
+
console.log(`\n负数: ${negNum}`);
|
|
53
|
+
console.log(`${negNum} >> 1 = ${negNum >> 1} (保留符号)`);
|
|
54
|
+
console.log(`${negNum} >>> 1 = ${negNum >>> 1} (不保留符号)`);
|
|
55
|
+
}
|
|
56
|
+
// #endregion
|
|
57
|
+
// #region 示例3: 权限管理系统
|
|
58
|
+
// 定义权限常量(使用位标志)
|
|
59
|
+
const PERMISSION = {
|
|
60
|
+
READ: 1 << 0, // 0001 = 1
|
|
61
|
+
WRITE: 1 << 1, // 0010 = 2
|
|
62
|
+
DELETE: 1 << 2, // 0100 = 4
|
|
63
|
+
EXECUTE: 1 << 3 // 1000 = 8
|
|
64
|
+
};
|
|
65
|
+
function permissionSystem() {
|
|
66
|
+
console.log('\n=== 权限管理系统 ===');
|
|
67
|
+
console.log('权限定义:');
|
|
68
|
+
console.log(`READ: ${PERMISSION.READ} (${PERMISSION.READ.toString(2).padStart(4, '0')})`);
|
|
69
|
+
console.log(`WRITE: ${PERMISSION.WRITE} (${PERMISSION.WRITE.toString(2).padStart(4, '0')})`);
|
|
70
|
+
console.log(`DELETE: ${PERMISSION.DELETE} (${PERMISSION.DELETE.toString(2).padStart(4, '0')})`);
|
|
71
|
+
console.log(`EXECUTE: ${PERMISSION.EXECUTE} (${PERMISSION.EXECUTE.toString(2).padStart(4, '0')})`);
|
|
72
|
+
// 授予多个权限(使用位或)
|
|
73
|
+
let userPermissions = PERMISSION.READ | PERMISSION.WRITE;
|
|
74
|
+
console.log(`\n用户权限: ${userPermissions} (${userPermissions.toString(2).padStart(4, '0')})`);
|
|
75
|
+
// 检查权限(使用位与)
|
|
76
|
+
const hasRead = (userPermissions & PERMISSION.READ) !== 0;
|
|
77
|
+
const hasDelete = (userPermissions & PERMISSION.DELETE) !== 0;
|
|
78
|
+
console.log(`\n有读权限: ${hasRead}`);
|
|
79
|
+
console.log(`有删除权限: ${hasDelete}`);
|
|
80
|
+
// 添加权限
|
|
81
|
+
userPermissions |= PERMISSION.EXECUTE;
|
|
82
|
+
console.log(`\n添加执行权限后: ${userPermissions} (${userPermissions.toString(2).padStart(4, '0')})`);
|
|
83
|
+
// 移除权限(使用位与和位非)
|
|
84
|
+
userPermissions &= ~PERMISSION.WRITE;
|
|
85
|
+
console.log(`移除写权限后: ${userPermissions} (${userPermissions.toString(2).padStart(4, '0')})`);
|
|
86
|
+
// 切换权限(使用位异或)
|
|
87
|
+
userPermissions ^= PERMISSION.READ;
|
|
88
|
+
console.log(`切换读权限后: ${userPermissions} (${userPermissions.toString(2).padStart(4, '0')})`);
|
|
89
|
+
}
|
|
90
|
+
// #endregion
|
|
91
|
+
// #region 示例4: 颜色处理
|
|
92
|
+
function colorProcessing() {
|
|
93
|
+
console.log('\n=== 颜色处理(RGB) ===');
|
|
94
|
+
// RGB 颜色值存储在一个 32 位整数中
|
|
95
|
+
// 格式: 0xRRGGBB
|
|
96
|
+
const color = 0xFF5733; // 橙红色
|
|
97
|
+
console.log(`颜色值: 0x${color.toString(16).toUpperCase()}`);
|
|
98
|
+
// 提取 RGB 分量
|
|
99
|
+
const red = (color >> 16) & 0xFF;
|
|
100
|
+
const green = (color >> 8) & 0xFF;
|
|
101
|
+
const blue = color & 0xFF;
|
|
102
|
+
console.log(`\nRGB 分量:`);
|
|
103
|
+
console.log(`R: ${red} (0x${red.toString(16).toUpperCase()})`);
|
|
104
|
+
console.log(`G: ${green} (0x${green.toString(16).toUpperCase()})`);
|
|
105
|
+
console.log(`B: ${blue} (0x${blue.toString(16).toUpperCase()})`);
|
|
106
|
+
// 组合 RGB 分量
|
|
107
|
+
const newColor = (red << 16) | (green << 8) | blue;
|
|
108
|
+
console.log(`\n重新组合: 0x${newColor.toString(16).toUpperCase()}`);
|
|
109
|
+
// 修改颜色分量
|
|
110
|
+
const darkerRed = Math.max(0, red - 50);
|
|
111
|
+
const darkerColor = (darkerRed << 16) | (green << 8) | blue;
|
|
112
|
+
console.log(`\n降低红色分量后: 0x${darkerColor.toString(16).toUpperCase()}`);
|
|
113
|
+
}
|
|
114
|
+
// #endregion
|
|
115
|
+
// #region 示例5: 实用位运算技巧
|
|
116
|
+
function bitwiseTricks() {
|
|
117
|
+
console.log('\n=== 实用位运算技巧 ===');
|
|
118
|
+
// 判断奇偶
|
|
119
|
+
const num1 = 7;
|
|
120
|
+
const num2 = 8;
|
|
121
|
+
console.log(`${num1} 是奇数: ${(num1 & 1) === 1}`);
|
|
122
|
+
console.log(`${num2} 是奇数: ${(num2 & 1) === 1}`);
|
|
123
|
+
// 交换两个数(不使用临时变量)
|
|
124
|
+
let a = 5;
|
|
125
|
+
let b = 10;
|
|
126
|
+
console.log(`\n交换前: a = ${a}, b = ${b}`);
|
|
127
|
+
a ^= b;
|
|
128
|
+
b ^= a;
|
|
129
|
+
a ^= b;
|
|
130
|
+
console.log(`交换后: a = ${a}, b = ${b}`);
|
|
131
|
+
// 取绝对值
|
|
132
|
+
const n = -42;
|
|
133
|
+
const mask = n >> 31; // 负数为 -1,正数为 0
|
|
134
|
+
const abs = (n + mask) ^ mask;
|
|
135
|
+
console.log(`\n${n} 的绝对值: ${abs}`);
|
|
136
|
+
// 判断是否为 2 的幂
|
|
137
|
+
function isPowerOfTwo(n) {
|
|
138
|
+
return (n & (n - 1)) === 0 && n !== 0;
|
|
139
|
+
}
|
|
140
|
+
const power1 = 16;
|
|
141
|
+
const power2 = 15;
|
|
142
|
+
console.log(`\n${power1} 是 2 的幂: ${isPowerOfTwo(power1)}`);
|
|
143
|
+
console.log(`${power2} 是 2 的幂: ${isPowerOfTwo(power2)}`);
|
|
144
|
+
// 向下取整到最接近的 2 的幂
|
|
145
|
+
function floorPowerOfTwo(n) {
|
|
146
|
+
n |= n >> 1;
|
|
147
|
+
n |= n >> 2;
|
|
148
|
+
n |= n >> 4;
|
|
149
|
+
n |= n >> 8;
|
|
150
|
+
n |= n >> 16;
|
|
151
|
+
return n - (n >> 1);
|
|
152
|
+
}
|
|
153
|
+
const num = 100;
|
|
154
|
+
console.log(`\n${num} 向下取整到 2 的幂: ${floorPowerOfTwo(num)}`);
|
|
155
|
+
// 计算二进制中 1 的个数
|
|
156
|
+
function countOnes(n) {
|
|
157
|
+
let count = 0;
|
|
158
|
+
while (n) {
|
|
159
|
+
n &= n - 1; // 清除最右边的 1
|
|
160
|
+
count++;
|
|
161
|
+
}
|
|
162
|
+
return count;
|
|
163
|
+
}
|
|
164
|
+
const testNum = 15; // 1111
|
|
165
|
+
console.log(`\n${testNum} (${testNum.toString(2)}) 中 1 的个数: ${countOnes(testNum)}`);
|
|
166
|
+
}
|
|
167
|
+
// #endregion
|
|
168
|
+
if (require.main === module) {
|
|
169
|
+
const examples = [
|
|
170
|
+
basicBitwiseOperators,
|
|
171
|
+
shiftOperators,
|
|
172
|
+
permissionSystem,
|
|
173
|
+
colorProcessing,
|
|
174
|
+
bitwiseTricks
|
|
175
|
+
];
|
|
176
|
+
const exampleNumber = parseInt(process.argv[2]);
|
|
177
|
+
if (exampleNumber && exampleNumber > 0 && exampleNumber <= examples.length) {
|
|
178
|
+
console.log(`\n运行示例 ${exampleNumber}:\n`);
|
|
179
|
+
examples[exampleNumber - 1]();
|
|
180
|
+
}
|
|
181
|
+
else {
|
|
182
|
+
console.log('运行所有示例:\n');
|
|
183
|
+
examples.forEach((example, index) => {
|
|
184
|
+
console.log(`\n${'='.repeat(50)}`);
|
|
185
|
+
console.log(`示例 ${index + 1}`);
|
|
186
|
+
console.log('='.repeat(50));
|
|
187
|
+
example();
|
|
188
|
+
});
|
|
189
|
+
}
|
|
190
|
+
}
|
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* TypeScript 表达式与求值
|
|
4
|
+
* =======================
|
|
5
|
+
* 涵盖三元运算符、逗号运算符、运算符优先级和表达式求值顺序
|
|
6
|
+
* 适用于 TypeScript 5.x
|
|
7
|
+
*/
|
|
8
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
9
|
+
exports.ternaryOperator = ternaryOperator;
|
|
10
|
+
exports.commaOperator = commaOperator;
|
|
11
|
+
exports.operatorPrecedence = operatorPrecedence;
|
|
12
|
+
exports.shortCircuitEvaluation = shortCircuitEvaluation;
|
|
13
|
+
exports.evaluationOrder = evaluationOrder;
|
|
14
|
+
// #region 示例1: 三元运算符
|
|
15
|
+
function ternaryOperator() {
|
|
16
|
+
console.log('=== 三元运算符 ===');
|
|
17
|
+
const age = 18;
|
|
18
|
+
const status = age >= 18 ? '成年人' : '未成年人';
|
|
19
|
+
console.log(`年龄 ${age}: ${status}`);
|
|
20
|
+
// 嵌套三元运算符
|
|
21
|
+
const score = 85;
|
|
22
|
+
const grade = score >= 90 ? 'A' :
|
|
23
|
+
score >= 80 ? 'B' :
|
|
24
|
+
score >= 70 ? 'C' :
|
|
25
|
+
score >= 60 ? 'D' : 'F';
|
|
26
|
+
console.log(`\n分数 ${score}: ${grade}`);
|
|
27
|
+
// 实际应用:条件渲染
|
|
28
|
+
const isLoggedIn = true;
|
|
29
|
+
const username = 'zhangsan';
|
|
30
|
+
const greeting = isLoggedIn ? `欢迎, ${username}!` : '请登录';
|
|
31
|
+
console.log(`\n${greeting}`);
|
|
32
|
+
// 与函数结合
|
|
33
|
+
const numbers = [1, 2, 3, 4, 5];
|
|
34
|
+
const result = numbers.map(n => n % 2 === 0 ? n * 2 : n);
|
|
35
|
+
console.log(`\n偶数翻倍: ${result}`);
|
|
36
|
+
}
|
|
37
|
+
// #endregion
|
|
38
|
+
// #region 示例2: 逗号运算符
|
|
39
|
+
function commaOperator() {
|
|
40
|
+
console.log('\n=== 逗号运算符 ===');
|
|
41
|
+
// 基本用法:返回最后一个表达式的值
|
|
42
|
+
let counter = 0;
|
|
43
|
+
let x = (counter++, counter++, counter++, counter++, counter);
|
|
44
|
+
console.log(`执行多个表达式后的值: ${x}`);
|
|
45
|
+
// 在 for 循环中使用
|
|
46
|
+
console.log('\nfor 循环中的逗号运算符:');
|
|
47
|
+
for (let i = 0, j = 10; i < 5; i++, j--) {
|
|
48
|
+
console.log(`i = ${i}, j = ${j}`);
|
|
49
|
+
}
|
|
50
|
+
// 在赋值中使用
|
|
51
|
+
let a = 0;
|
|
52
|
+
let b = (a = 1, a + 2);
|
|
53
|
+
console.log(`\na = ${a}, b = ${b}`);
|
|
54
|
+
// 实际应用:简化代码
|
|
55
|
+
function increment(value) {
|
|
56
|
+
return (console.log(`递增前: ${value}`), value + 1);
|
|
57
|
+
}
|
|
58
|
+
const newValue = increment(5);
|
|
59
|
+
console.log(`递增后: ${newValue}`);
|
|
60
|
+
}
|
|
61
|
+
// #endregion
|
|
62
|
+
// #region 示例3: 运算符优先级
|
|
63
|
+
function operatorPrecedence() {
|
|
64
|
+
console.log('\n=== 运算符优先级 ===');
|
|
65
|
+
// 算术运算符优先级
|
|
66
|
+
const result1 = 2 + 3 * 4;
|
|
67
|
+
const result2 = (2 + 3) * 4;
|
|
68
|
+
console.log(`2 + 3 * 4 = ${result1}`);
|
|
69
|
+
console.log(`(2 + 3) * 4 = ${result2}`);
|
|
70
|
+
// 比较和逻辑运算符
|
|
71
|
+
const result3 = 5 > 3 && 2 < 4;
|
|
72
|
+
const result4 = 5 > 3 || 2 > 4;
|
|
73
|
+
console.log(`\n5 > 3 && 2 < 4 = ${result3}`);
|
|
74
|
+
console.log(`5 > 3 || 2 > 4 = ${result4}`);
|
|
75
|
+
// 复杂表达式
|
|
76
|
+
const a = 10;
|
|
77
|
+
const b = 5;
|
|
78
|
+
const c = 2;
|
|
79
|
+
const result5 = a + b * c > 15 && a - b < 10;
|
|
80
|
+
console.log(`\n${a} + ${b} * ${c} > 15 && ${a} - ${b} < 10 = ${result5}`);
|
|
81
|
+
// 位运算符优先级
|
|
82
|
+
const result6 = 5 | 3 & 1; // & 优先级高于 |
|
|
83
|
+
const result7 = (5 | 3) & 1;
|
|
84
|
+
console.log(`\n5 | 3 & 1 = ${result6}`);
|
|
85
|
+
console.log(`(5 | 3) & 1 = ${result7}`);
|
|
86
|
+
}
|
|
87
|
+
// #endregion
|
|
88
|
+
// #region 示例4: 短路求值
|
|
89
|
+
function shortCircuitEvaluation() {
|
|
90
|
+
console.log('\n=== 短路求值 ===');
|
|
91
|
+
// 逻辑与短路
|
|
92
|
+
console.log('逻辑与 (&&) 短路:');
|
|
93
|
+
let count1 = 0;
|
|
94
|
+
const result1 = false && (count1++, true);
|
|
95
|
+
console.log(`result: ${result1}, count: ${count1}`); // count 不会增加
|
|
96
|
+
let count2 = 0;
|
|
97
|
+
const result2 = true && (count2++, true);
|
|
98
|
+
console.log(`result: ${result2}, count: ${count2}`); // count 会增加
|
|
99
|
+
// 逻辑或短路
|
|
100
|
+
console.log('\n逻辑或 (||) 短路:');
|
|
101
|
+
let count3 = 0;
|
|
102
|
+
const result3 = true || (count3++, false);
|
|
103
|
+
console.log(`result: ${result3}, count: ${count3}`); // count 不会增加
|
|
104
|
+
let count4 = 0;
|
|
105
|
+
const result4 = false || (count4++, true);
|
|
106
|
+
console.log(`result: ${result4}, count: ${count4}`); // count 会增加
|
|
107
|
+
// 实际应用:默认值
|
|
108
|
+
function greet(name) {
|
|
109
|
+
const displayName = name || '访客';
|
|
110
|
+
console.log(`\n你好, ${displayName}!`);
|
|
111
|
+
}
|
|
112
|
+
greet('张三');
|
|
113
|
+
greet();
|
|
114
|
+
// 实际应用:条件执行
|
|
115
|
+
const isDebug = true;
|
|
116
|
+
isDebug && console.log('\n调试模式已启用');
|
|
117
|
+
// 空值合并的短路
|
|
118
|
+
let nullValue = null;
|
|
119
|
+
const value1 = nullValue ?? '默认值';
|
|
120
|
+
let nonNullValue = 'hello';
|
|
121
|
+
const value2 = nonNullValue ?? '这不会使用';
|
|
122
|
+
console.log(`\nvalue1: ${value1}`);
|
|
123
|
+
console.log(`value2: ${value2}`);
|
|
124
|
+
}
|
|
125
|
+
// #endregion
|
|
126
|
+
// #region 示例5: 表达式求值顺序
|
|
127
|
+
function evaluationOrder() {
|
|
128
|
+
console.log('\n=== 表达式求值顺序 ===');
|
|
129
|
+
// 函数参数求值顺序(从左到右)
|
|
130
|
+
function log(a, b, c) {
|
|
131
|
+
console.log(`a=${a}, b=${b}, c=${c}`);
|
|
132
|
+
}
|
|
133
|
+
let counter = 0;
|
|
134
|
+
function next() {
|
|
135
|
+
return ++counter;
|
|
136
|
+
}
|
|
137
|
+
console.log('函数参数求值顺序:');
|
|
138
|
+
log(next(), next(), next());
|
|
139
|
+
// 赋值表达式求值
|
|
140
|
+
counter = 0;
|
|
141
|
+
let x = 0;
|
|
142
|
+
x = next() + next();
|
|
143
|
+
console.log(`\nx = next() + next() = ${x}`);
|
|
144
|
+
console.log(`counter = ${counter}`);
|
|
145
|
+
// 对象属性求值顺序
|
|
146
|
+
counter = 0;
|
|
147
|
+
const obj = {
|
|
148
|
+
a: next(),
|
|
149
|
+
b: next(),
|
|
150
|
+
c: next()
|
|
151
|
+
};
|
|
152
|
+
console.log(`\n对象属性: ${JSON.stringify(obj)}`);
|
|
153
|
+
// 数组元素求值顺序
|
|
154
|
+
counter = 0;
|
|
155
|
+
const arr = [next(), next(), next()];
|
|
156
|
+
console.log(`数组元素: ${JSON.stringify(arr)}`);
|
|
157
|
+
// 链式调用求值
|
|
158
|
+
console.log('\n链式调用求值:');
|
|
159
|
+
const calculator = {
|
|
160
|
+
value: 0,
|
|
161
|
+
add(n) {
|
|
162
|
+
console.log(` add(${n})`);
|
|
163
|
+
this.value += n;
|
|
164
|
+
return this;
|
|
165
|
+
},
|
|
166
|
+
multiply(n) {
|
|
167
|
+
console.log(` multiply(${n})`);
|
|
168
|
+
this.value *= n;
|
|
169
|
+
return this;
|
|
170
|
+
},
|
|
171
|
+
getResult() {
|
|
172
|
+
console.log(` getResult()`);
|
|
173
|
+
return this.value;
|
|
174
|
+
}
|
|
175
|
+
};
|
|
176
|
+
const result = calculator.add(5).multiply(2).add(3).getResult();
|
|
177
|
+
console.log(`最终结果: ${result}`);
|
|
178
|
+
}
|
|
179
|
+
// #endregion
|
|
180
|
+
if (require.main === module) {
|
|
181
|
+
const examples = [
|
|
182
|
+
ternaryOperator,
|
|
183
|
+
commaOperator,
|
|
184
|
+
operatorPrecedence,
|
|
185
|
+
shortCircuitEvaluation,
|
|
186
|
+
evaluationOrder
|
|
187
|
+
];
|
|
188
|
+
const exampleNumber = parseInt(process.argv[2]);
|
|
189
|
+
if (exampleNumber && exampleNumber > 0 && exampleNumber <= examples.length) {
|
|
190
|
+
console.log(`\n运行示例 ${exampleNumber}:\n`);
|
|
191
|
+
examples[exampleNumber - 1]();
|
|
192
|
+
}
|
|
193
|
+
else {
|
|
194
|
+
console.log('运行所有示例:\n');
|
|
195
|
+
examples.forEach((example, index) => {
|
|
196
|
+
console.log(`\n${'='.repeat(50)}`);
|
|
197
|
+
console.log(`示例 ${index + 1}`);
|
|
198
|
+
console.log('='.repeat(50));
|
|
199
|
+
example();
|
|
200
|
+
});
|
|
201
|
+
}
|
|
202
|
+
}
|