当前位置: 首页 > news >正文

TS项目实战二:网页计算器

  使用ts实现网页计算器工具,实现计算器相关功能,使用tsify进行项目编译,引入Browserify实现web界面中直接使用模块加载服务。
  源码下载:点击下载

  1. 讲解视频

    TS实战项目四:计算器项目创建


    TS实战项目五:Browserify安装配置

  2. B站视频

    TS实战项目四:计算器项目创建


    TS实战项目五:Browserify安装配置

  3. 西瓜视频
    https://www.ixigua.com/7329331349171470899

一.知识点

1. tsify编译
2. tsconfig.json配置项
3. 模块定义及导入导出
4. 类定义
5. 参数属性
6. 存取器
7. 接口定义
8. 命名空间
9. 函数重载
10. 事件处理

二.效果预览

在这里插入图片描述

三.实现思路

  使用ui和逻辑控制分离的模式,实现ui绘制及计算数据的单独处理,自定义按钮、输入框等ui组件,并绘制到界面中;通过事件监听的方式实现按钮点击后对应的逻辑控制,入结果计算、结果展示等。

四.创建项目

1. 创建node项目,使用npm init命令,如下:

在这里插入图片描述

2. 安装ts库,npm install typescript --save:

在这里插入图片描述

3. .\node_modules.bin\tsc --init生成ts的项目配置文件,此处注意直接用vscode的powershell运行的时候会保存,请切换到cmd命令窗口执行命令:

在这里插入图片描述

4. 安装lite-server库,npm install lite-server,安装完毕后添加"start": "lite-server"指令,用于提供web服务:

在这里插入图片描述

5. 安装Browserify,npm install tsify,提供浏览器环境中进行模块加载器的相关支持,具体文档参见:https://github.com/smrq/tsify,可创建bs-config.js文件进行web服务的配置。

在这里插入图片描述

6. 安装后创建build.js文件,用于进行ts代码的编译处理:

在这里插入图片描述

7. 在package.json中添加编译指令:

"build-cli": "browserify -p tsify ./src/index.ts > ./dist/index.js",
"build-script": "node ./build.js > ./dist/index.js",

在这里插入图片描述

8. 创建dist文件夹,并创建index.html文件,实现web界面:

在这里插入图片描述

9. 创建后项目目录结构如下:

在这里插入图片描述

五.编码实现

1. tsconfig.json

{"compilerOptions": {/* Visit https://aka.ms/tsconfig to read more about this file *//* Projects */// "incremental": true,                              /* Save .tsbuildinfo files to allow for incremental compilation of projects. */// "composite": true,                                /* Enable constraints that allow a TypeScript project to be used with project references. */// "tsBuildInfoFile": "./.tsbuildinfo",              /* Specify the path to .tsbuildinfo incremental compilation file. */// "disableSourceOfProjectReferenceRedirect": true,  /* Disable preferring source files instead of declaration files when referencing composite projects. */// "disableSolutionSearching": true,                 /* Opt a project out of multi-project reference checking when editing. */// "disableReferencedProjectLoad": true,             /* Reduce the number of projects loaded automatically by TypeScript. *//* Language and Environment */"target": "es2016", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */// "lib": [],                                        /* Specify a set of bundled library declaration files that describe the target runtime environment. */// "jsx": "preserve",                                /* Specify what JSX code is generated. */// "experimentalDecorators": true,                   /* Enable experimental support for legacy experimental decorators. */// "emitDecoratorMetadata": true,                    /* Emit design-type metadata for decorated declarations in source files. */// "jsxFactory": "",                                 /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */// "jsxFragmentFactory": "",                         /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */// "jsxImportSource": "",                            /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */// "reactNamespace": "",                             /* Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit. */// "noLib": true,                                    /* Disable including any library files, including the default lib.d.ts. */// "useDefineForClassFields": true,                  /* Emit ECMAScript-standard-compliant class fields. */// "moduleDetection": "auto",                        /* Control what method is used to detect module-format JS files. *//* Modules */"module": "commonjs", /* Specify what module code is generated. */"rootDir": "./", /* Specify the root folder within your source files. */// "moduleResolution": "node10",                     /* Specify how TypeScript looks up a file from a given module specifier. */// "baseUrl": "./",                                  /* Specify the base directory to resolve non-relative module names. */// "paths": {},                                      /* Specify a set of entries that re-map imports to additional lookup locations. */// "rootDirs": [],                                   /* Allow multiple folders to be treated as one when resolving modules. */// "typeRoots": [],                                  /* Specify multiple folders that act like './node_modules/@types'. */// "types": [],                                      /* Specify type package names to be included without being referenced in a source file. */// "allowUmdGlobalAccess": true,                     /* Allow accessing UMD globals from modules. */// "moduleSuffixes": [],                             /* List of file name suffixes to search when resolving a module. */// "allowImportingTsExtensions": true,               /* Allow imports to include TypeScript file extensions. Requires '--moduleResolution bundler' and either '--noEmit' or '--emitDeclarationOnly' to be set. */// "resolvePackageJsonExports": true,                /* Use the package.json 'exports' field when resolving package imports. */// "resolvePackageJsonImports": true,                /* Use the package.json 'imports' field when resolving imports. */// "customConditions": [],                           /* Conditions to set in addition to the resolver-specific defaults when resolving imports. */// "resolveJsonModule": true,                        /* Enable importing .json files. */// "allowArbitraryExtensions": true,                 /* Enable importing files with any extension, provided a declaration file is present. */// "noResolve": true,                                /* Disallow 'import's, 'require's or '<reference>'s from expanding the number of files TypeScript should add to a project. *//* JavaScript Support */// "allowJs": true,                                  /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */// "checkJs": true,                                  /* Enable error reporting in type-checked JavaScript files. */// "maxNodeModuleJsDepth": 1,                        /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. *//* Emit */// "declaration": true,                              /* Generate .d.ts files from TypeScript and JavaScript files in your project. */// "declarationMap": true,                           /* Create sourcemaps for d.ts files. */// "emitDeclarationOnly": true,                      /* Only output d.ts files and not JavaScript files. */"sourceMap": true, /* Create source map files for emitted JavaScript files. */// "inlineSourceMap": true,                          /* Include sourcemap files inside the emitted JavaScript. */// "outFile": "./",                                  /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */"outDir": "./dist", /* Specify an output folder for all emitted files. */// "removeComments": true,                           /* Disable emitting comments. */// "noEmit": true,                                   /* Disable emitting files from a compilation. */// "importHelpers": true,                            /* Allow importing helper functions from tslib once per project, instead of including them per-file. */// "importsNotUsedAsValues": "remove",               /* Specify emit/checking behavior for imports that are only used for types. */// "downlevelIteration": true,                       /* Emit more compliant, but verbose and less performant JavaScript for iteration. */// "sourceRoot": "",                                 /* Specify the root path for debuggers to find the reference source code. */// "mapRoot": "",                                    /* Specify the location where debugger should locate map files instead of generated locations. */// "inlineSources": true,                            /* Include source code in the sourcemaps inside the emitted JavaScript. */// "emitBOM": true,                                  /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */// "newLine": "crlf",                                /* Set the newline character for emitting files. */// "stripInternal": true,                            /* Disable emitting declarations that have '@internal' in their JSDoc comments. */// "noEmitHelpers": true,                            /* Disable generating custom helper functions like '__extends' in compiled output. */// "noEmitOnError": true,                            /* Disable emitting files if any type checking errors are reported. */// "preserveConstEnums": true,                       /* Disable erasing 'const enum' declarations in generated code. */// "declarationDir": "./",                           /* Specify the output directory for generated declaration files. */// "preserveValueImports": true,                     /* Preserve unused imported values in the JavaScript output that would otherwise be removed. *//* Interop Constraints */// "isolatedModules": true,                          /* Ensure that each file can be safely transpiled without relying on other imports. */// "verbatimModuleSyntax": true,                     /* Do not transform or elide any imports or exports not marked as type-only, ensuring they are written in the output file's format based on the 'module' setting. */// "allowSyntheticDefaultImports": true,             /* Allow 'import x from y' when a module doesn't have a default export. */"esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */// "preserveSymlinks": true,                         /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */"forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. *//* Type Checking */"strict": true, /* Enable all strict type-checking options. */// "noImplicitAny": true,                            /* Enable error reporting for expressions and declarations with an implied 'any' type. */// "strictNullChecks": true,                         /* When type checking, take into account 'null' and 'undefined'. */// "strictFunctionTypes": true,                      /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */// "strictBindCallApply": true,                      /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */// "strictPropertyInitialization": true,             /* Check for class properties that are declared but not set in the constructor. */// "noImplicitThis": true,                           /* Enable error reporting when 'this' is given the type 'any'. */// "useUnknownInCatchVariables": true,               /* Default catch clause variables as 'unknown' instead of 'any'. */// "alwaysStrict": true,                             /* Ensure 'use strict' is always emitted. */// "noUnusedLocals": true,                           /* Enable error reporting when local variables aren't read. */// "noUnusedParameters": true,                       /* Raise an error when a function parameter isn't read. */// "exactOptionalPropertyTypes": true,               /* Interpret optional property types as written, rather than adding 'undefined'. */// "noImplicitReturns": true,                        /* Enable error reporting for codepaths that do not explicitly return in a function. */// "noFallthroughCasesInSwitch": true,               /* Enable error reporting for fallthrough cases in switch statements. */// "noUncheckedIndexedAccess": true,                 /* Add 'undefined' to a type when accessed using an index. */// "noImplicitOverride": true,                       /* Ensure overriding members in derived classes are marked with an override modifier. */// "noPropertyAccessFromIndexSignature": true,       /* Enforces using indexed accessors for keys declared using an indexed type. */// "allowUnusedLabels": true,                        /* Disable error reporting for unused labels. */// "allowUnreachableCode": true,                     /* Disable error reporting for unreachable code. *//* Completeness */// "skipDefaultLibCheck": true,                      /* Skip type checking .d.ts files that are included with TypeScript. */"skipLibCheck": true /* Skip type checking all .d.ts files. */}
}

2. package.json

{"name": "demo2","version": "1.0.0","description": "","main": "./src/index.ts","scripts": {"build-cli": "browserify -p tsify ./src/index.ts > ./dist/index.js","build-script": "node ./build.js > ./dist/index.js","start": "lite-server"},"author": "","license": "ISC","dependencies": {"browserify": "^17.0.0","lite-server": "^2.6.1","tsify": "^5.0.4","typescript": "^5.3.3"}
}

3. build.js

var browserify = require('browserify');
var tsify = require('tsify');browserify().add('./src/index.ts').plugin(tsify, { noImplicitAny: true }).bundle().on('error', function (error) { console.error(error.toString()); }).pipe(process.stdout);

4. bs-config.js

"use strict";
module.exports = {port: 8080,files: ['./dist/**/*.{html,css,js}'],server: {baseDir: './dist'}
}

5. index.html

<!DOCTYPE html>
<html lang="en"><head><meta charset="UTF-8"><link rel="icon" href="/favicon.ico"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>计算器演示</title><style>html,body {width: 100%;height: 100%;margin: 0px;padding: 0px;}#app {display: flex;justify-content: center;justify-items: center;align-items: center;height: 100vh;}#app .panel {margin: 0 auto;width: 300px;height: 410px;border: 1px solid #f8f8f8;background-color: #f5f5f5;box-shadow: 0 0 4px 4px #d7d7d7b5;border-radius: 5px;}#app .panel .result {font-size: 30px;font-weight: bold;text-align: right;height: 60px;line-height: 60px;padding: 10px;padding-bottom: 0px;user-select: none;}#app .panel .buttons .line {display: flex;height: 55px;line-height: 55px;width: 100%;}#app .panel .buttons .line .btnPanel {padding: 5px;flex: 1;}#app .panel .buttons .line .btnPanel button {width: 100%;height: 100%;border-radius: 5px;border: 1px solid #eee;cursor: pointer;background-color: #fff;user-select: none;font-size: 18px;}#app .panel .buttons .line .btnPanel button:hover {background-color: #00adff;color: #fff;}#app .panel .buttons .line .btnPanel button.eq {background-color: #00adff;color: #fff;border: 1px solid #00adff;border-radius: 5px;}</style></head><body><div id="app"></div><script src="./index.js"></script><script></script></body></html>

6. src/index.ts

import ProcessFactory from './ProcessFactory';
import UI from './ui/UI';const ui = new UI();//初始化
ui.init(document.getElementById('app'), ProcessFactory);

7. src/ProcessFactory.ts

import BackProcess from './proecess/BackProcess';
import BaseProcess from './proecess/BaseProcess';
import CProcess from './proecess/CProcess';
import EqProcess from './proecess/EqProcess';
import FenProcess from './proecess/FenProcess';
import NumberProcess from './proecess/NumerProcess';
import OpratorProcess from './proecess/OpratorProcess';
import PercentProcess from './proecess/PercentProcess';
import PinFangProcess from './proecess/PinFangProcess';
import PointProcess from './proecess/PointProcess';
import SqtProcess from './proecess/SqtProcess';/*** 处理器的工厂函数,根据不同的字符,生成不同的处理器*/
export default function getProcess(char: string): BaseProcess | null {if (char == '0' || char == '1' || char == '2' || char == '3' || char == '4' || char == '5' || char == '6' || char == '7' || char == '8' || char == '9') {return new NumberProcess(char);}if (char == '.') {return new PointProcess(char);}if (char == '=') {return new EqProcess(char);}if (char == '+' || char == '-' || char == '*' || char == '/') {return new OpratorProcess(char);}if (char == 'C') {return new CProcess(char);}if (char == '←') {return new BackProcess(char);}if (char == '%') {return new PercentProcess(char);}if (char == '1/x') {return new FenProcess(char);}if (char == 'x^2') {return new PinFangProcess(char);}if (char == '根号') {return new SqtProcess(char);}return null;
}

8. src/ui/UI.ts

/*** 根容器*/
const rootPanel: HTMLDivElement = document.createElement('div');//展示结果
const resultPanel: HTMLDivElement = document.createElement('div');//按钮容器
const buttonPanel: HTMLDivElement = document.createElement('div');//按钮
const btns: string[][] = [['%', 'CE', 'C', '←'],['1/x', 'x^2', '根号', '/'],['7', '8', '9', '*'],['4', '5', '6', '-'],['1', '2', '3', '+'],['0', '.', '=']
];//计算结果
let result = "0";/*** UI工具*/
export default class UI {/*** 初始化界面* @param root */init(root: HTMLElement | null, getProcess: Function): HTMLDivElement {if (!root) {throw new Error('必须要指定根元素');}//设置类,控制样式rootPanel.className = 'panel';resultPanel.className = 'result';resultPanel.innerText = result;rootPanel.appendChild(resultPanel);buttonPanel.className = "buttons";btns.forEach(item => {let linePanel: HTMLDivElement = document.createElement('div');linePanel.className = 'line';item.forEach(text => {let buttonPanel: HTMLDivElement = document.createElement('div');buttonPanel.className = 'btnPanel';let button: HTMLButtonElement = document.createElement('button');button.innerText = text + "";if (text === '=') {button.className = 'eq';}//附加按钮的标识,记录具体是什么内容button.setAttribute('content', text);let process = getProcess(text);if (process) {button.onclick = () => {result = process.process(result);updateReslt();};}buttonPanel.appendChild(button);linePanel.appendChild(buttonPanel);})buttonPanel.appendChild(linePanel);})rootPanel.appendChild(buttonPanel);//生成具体的元素root.appendChild(rootPanel);return rootPanel;}
}
/*** 更新计算结果*/
function updateReslt() {resultPanel.innerText = result;
}

9. src/process/BaseProcess.ts

/*** 处理器*/
export default interface BaseProcess {/*** 要处理的字符串*/char: string;/*** 按钮点击后计算结构* @param value  按钮的值* @param result 计算原始的结果*/process(result: string): string;
}

10. src/process/BackProcess.ts

import BaseProcess from './BaseProcess';/*** 删除按钮的处理*/
export default class BackProcess implements BaseProcess {char: string;constructor(char_: string) {this.char = char_;}/***删除的处理* @param result * @returns */process(result: string): string {if (result.length > 0) {let result_ = result?.substring(0, result.length - 1);return result_ ? result_ : '0';}return '0';}
}

11. src/process/EqProcess.ts

import BaseProcess from './BaseProcess';/*** 等于号的处理*/
export default class EqProcess implements BaseProcess {char: string;constructor(char_: string) {this.char = char_;}/***清空的处理* @param result * @returns */process(result?: string): string {return '0';}
}

12. src/process/EqProcess.ts

import BaseProcess from './BaseProcess';/*** 等于号的处理*/
export default class EqProcess implements BaseProcess {char: string;constructor(char_: string) {this.char = char_;}/*** 等于号的处理* @param value 空值* @param result * @returns */process(result: string): string {/*** 计算结果:1+2-3/4*5*/while (result.indexOf('+') != -1 || result.indexOf('-') != -1 || result.indexOf('/') != -1 || result.indexOf('*') != -1) {//先计算乘除let chenIndex = result.indexOf('*');let chuIndex = result.indexOf('/');while (chenIndex >= 0 || chuIndex >= 0) {if (chenIndex >= 0 && chuIndex >= 0) {//有乘的计算、也有除的计算if (chenIndex < chuIndex) {//乘在前result = this.jisuan('*', result, chenIndex);} else {result = this.jisuan('/', result, chuIndex);}} else {if (chenIndex >= 0) {result = this.jisuan('*', result, chenIndex);} else if (chuIndex >= 0) {result = this.jisuan('/', result, chuIndex);}}chenIndex = result.indexOf('*');chuIndex = result.indexOf('/');}let jiaIndex = result.indexOf('+');let jianIndex = result.indexOf('-');if (jiaIndex >= 0 && jianIndex >= 0) {//计算加减if (jiaIndex < jianIndex) {result = this.jisuan('+', result, jiaIndex);} else {result = this.jisuan('-', result, jianIndex);}} else {if (jiaIndex >= 0) {result = this.jisuan('+', result, jiaIndex);} else if (jianIndex >= 0) {result = this.jisuan('-', result, jianIndex);}}}return result;}jisuan(op: string, result: string, index: number): string {let preStr = '';let startIndex = 0;for (let i = index - 1; i >= 0 && (result.charAt(i) !== '*' && result.charAt(i) !== '/' && result.charAt(i) !== '+' && result.charAt(i) !== '-'); i--) {preStr += result[i];startIndex = i;}//反转preStr = preStr.split('').reverse().join('');let nexStr = '';let endIndex = 0;for (let i = index + 1; i < result.length && (result.charAt(i) !== '*' && result.charAt(i) !== '/' && result.charAt(i) !== '+' && result.charAt(i) !== '-'); i++) {nexStr += result[i];endIndex = i;}let preNum = parseFloat(preStr);let nextNum = parseFloat(nexStr);let result_ = '';for (let i = 0; i < result.length; i++) {if (i >= startIndex && i <= endIndex) {if (i == startIndex) {if (op == '*') {result_ += (preNum * nextNum) + '';} else if (op == '/') {result_ += (preNum / nextNum) + '';} else if (op == '+') {result_ += (preNum + nextNum) + '';} else {result_ += (preNum - nextNum) + '';}}continue;}result_ += result.charAt(i);}return result_;}
}

13. src/process/FenProcess.ts

import BaseProcess from './BaseProcess';/*** 几分之几的处理*/
export default class FenProcess implements BaseProcess {char: string;constructor(char_: string) {this.char = char_;}/*** 几分之几的处理* @param value 空值* @param result * @returns */process(result: string): string {/*** 计算结果:1+2-3/4*5*/while (result.indexOf('+') != -1 || result.indexOf('-') != -1 || result.indexOf('/') != -1 || result.indexOf('*') != -1) {//先计算乘除let chenIndex = result.indexOf('*');let chuIndex = result.indexOf('/');while (chenIndex >= 0 || chuIndex >= 0) {if (chenIndex >= 0 && chuIndex >= 0) {//有乘的计算、也有除的计算if (chenIndex < chuIndex) {//乘在前result = this.jisuan('*', result, chenIndex);} else {result = this.jisuan('/', result, chuIndex);}} else {if (chenIndex >= 0) {result = this.jisuan('*', result, chenIndex);} else if (chuIndex >= 0) {result = this.jisuan('/', result, chuIndex);}}chenIndex = result.indexOf('*');chuIndex = result.indexOf('/');}let jiaIndex = result.indexOf('+');let jianIndex = result.indexOf('-');if (jiaIndex >= 0 && jianIndex >= 0) {//计算加减if (jiaIndex < jianIndex) {result = this.jisuan('+', result, jiaIndex);} else {result = this.jisuan('-', result, jianIndex);}} else {if (jiaIndex >= 0) {result = this.jisuan('+', result, jiaIndex);} else if (jianIndex >= 0) {result = this.jisuan('-', result, jianIndex);}}}return (1 / parseFloat(result)) + '';}jisuan(op: string, result: string, index: number): string {let preStr = '';let startIndex = 0;for (let i = index - 1; i >= 0 && (result.charAt(i) !== '*' && result.charAt(i) !== '/' && result.charAt(i) !== '+' && result.charAt(i) !== '-'); i--) {preStr += result[i];startIndex = i;}//反转preStr = preStr.split('').reverse().join('');let nexStr = '';let endIndex = 0;for (let i = index + 1; i < result.length && (result.charAt(i) !== '*' && result.charAt(i) !== '/' && result.charAt(i) !== '+' && result.charAt(i) !== '-'); i++) {nexStr += result[i];endIndex = i;}let preNum = parseFloat(preStr);let nextNum = parseFloat(nexStr);let result_ = '';for (let i = 0; i < result.length; i++) {if (i >= startIndex && i <= endIndex) {if (i == startIndex) {if (op == '*') {result_ += (preNum * nextNum) + '';} else if (op == '/') {result_ += (preNum / nextNum) + '';} else if (op == '+') {result_ += (preNum + nextNum) + '';} else {result_ += (preNum - nextNum) + '';}}continue;}result_ += result.charAt(i);}return result_;}
}

14. src/process/NumerProcess.ts

import BaseProcess from './BaseProcess';/*** 计算数字型的按钮*/
export default class NumberProcess implements BaseProcess {char: string;constructor(char_: string) {this.char = char_;}/*** 计算结果,传入的是数字按钮* @param value 数字* @param result 现有的结果* @returns 合并后的值*/process(result: string): string {if (this.char == '0') {if (parseFloat(result) == 0) {return '0';}}if (parseFloat(result) == 0 && result.indexOf('.') == -1) {return this.char;} else {return result + '' + this.char;}}
}

15. src/process/OpratorProcess.ts

import BaseProcess from './BaseProcess';/*** 实现操作符的处理*/
export default class OpratorProcess implements BaseProcess {char: string;constructor(char_: string) {this.char = char_;}/*** 操作符的处理,+,-,*,/* @param result * @returns 合并后的结果*/process(result: string): string {if (result.charAt(result.length - 1) == '+' || result.charAt(result.length - 1) == '-' || result.charAt(result.length - 1) == '*' || result.charAt(result.length - 1) == '/') {return result;}return '' + result + this.char;}
}

16. src/process/PercentProcess.ts

import BaseProcess from './BaseProcess';/*** 百分号的处理*/
export default class PercentProcess implements BaseProcess {char: string;constructor(char_: string) {this.char = char_;}/*** 百分号的处理* @param value 空值* @param result * @returns */process(result: string): string {/*** 计算结果:1+2-3/4*5*/while (result.indexOf('+') != -1 || result.indexOf('-') != -1 || result.indexOf('/') != -1 || result.indexOf('*') != -1) {//先计算乘除let chenIndex = result.indexOf('*');let chuIndex = result.indexOf('/');while (chenIndex >= 0 || chuIndex >= 0) {if (chenIndex >= 0 && chuIndex >= 0) {//有乘的计算、也有除的计算if (chenIndex < chuIndex) {//乘在前result = this.jisuan('*', result, chenIndex);} else {result = this.jisuan('/', result, chuIndex);}} else {if (chenIndex >= 0) {result = this.jisuan('*', result, chenIndex);} else if (chuIndex >= 0) {result = this.jisuan('/', result, chuIndex);}}chenIndex = result.indexOf('*');chuIndex = result.indexOf('/');}let jiaIndex = result.indexOf('+');let jianIndex = result.indexOf('-');if (jiaIndex >= 0 && jianIndex >= 0) {//计算加减if (jiaIndex < jianIndex) {result = this.jisuan('+', result, jiaIndex);} else {result = this.jisuan('-', result, jianIndex);}} else {if (jiaIndex >= 0) {result = this.jisuan('+', result, jiaIndex);} else if (jianIndex >= 0) {result = this.jisuan('-', result, jianIndex);}}}return (parseFloat(result) / 100) + '';}jisuan(op: string, result: string, index: number): string {let preStr = '';let startIndex = 0;for (let i = index - 1; i >= 0 && (result.charAt(i) !== '*' && result.charAt(i) !== '/' && result.charAt(i) !== '+' && result.charAt(i) !== '-'); i--) {preStr += result[i];startIndex = i;}//反转preStr = preStr.split('').reverse().join('');let nexStr = '';let endIndex = 0;for (let i = index + 1; i < result.length && (result.charAt(i) !== '*' && result.charAt(i) !== '/' && result.charAt(i) !== '+' && result.charAt(i) !== '-'); i++) {nexStr += result[i];endIndex = i;}let preNum = parseFloat(preStr);let nextNum = parseFloat(nexStr);let result_ = '';for (let i = 0; i < result.length; i++) {if (i >= startIndex && i <= endIndex) {if (i == startIndex) {if (op == '*') {result_ += (preNum * nextNum) + '';} else if (op == '/') {result_ += (preNum / nextNum) + '';} else if (op == '+') {result_ += (preNum + nextNum) + '';} else {result_ += (preNum - nextNum) + '';}}continue;}result_ += result.charAt(i);}return result_;}
}

17. src/process/PinFangProcess.ts

import BaseProcess from './BaseProcess';/*** 几分之几的处理*/
export default class PinFangProcess implements BaseProcess {char: string;constructor(char_: string) {this.char = char_;}/*** 几分之几的处理* @param value 空值* @param result * @returns */process(result: string): string {/*** 计算结果:1+2-3/4*5*/while (result.indexOf('+') != -1 || result.indexOf('-') != -1 || result.indexOf('/') != -1 || result.indexOf('*') != -1) {//先计算乘除let chenIndex = result.indexOf('*');let chuIndex = result.indexOf('/');while (chenIndex >= 0 || chuIndex >= 0) {if (chenIndex >= 0 && chuIndex >= 0) {//有乘的计算、也有除的计算if (chenIndex < chuIndex) {//乘在前result = this.jisuan('*', result, chenIndex);} else {result = this.jisuan('/', result, chuIndex);}} else {if (chenIndex >= 0) {result = this.jisuan('*', result, chenIndex);} else if (chuIndex >= 0) {result = this.jisuan('/', result, chuIndex);}}chenIndex = result.indexOf('*');chuIndex = result.indexOf('/');}let jiaIndex = result.indexOf('+');let jianIndex = result.indexOf('-');if (jiaIndex >= 0 && jianIndex >= 0) {//计算加减if (jiaIndex < jianIndex) {result = this.jisuan('+', result, jiaIndex);} else {result = this.jisuan('-', result, jianIndex);}} else {if (jiaIndex >= 0) {result = this.jisuan('+', result, jiaIndex);} else if (jianIndex >= 0) {result = this.jisuan('-', result, jianIndex);}}}return (parseFloat(result) * parseFloat(result)) + '';}jisuan(op: string, result: string, index: number): string {let preStr = '';let startIndex = 0;for (let i = index - 1; i >= 0 && (result.charAt(i) !== '*' && result.charAt(i) !== '/' && result.charAt(i) !== '+' && result.charAt(i) !== '-'); i--) {preStr += result[i];startIndex = i;}//反转preStr = preStr.split('').reverse().join('');let nexStr = '';let endIndex = 0;for (let i = index + 1; i < result.length && (result.charAt(i) !== '*' && result.charAt(i) !== '/' && result.charAt(i) !== '+' && result.charAt(i) !== '-'); i++) {nexStr += result[i];endIndex = i;}let preNum = parseFloat(preStr);let nextNum = parseFloat(nexStr);let result_ = '';for (let i = 0; i < result.length; i++) {if (i >= startIndex && i <= endIndex) {if (i == startIndex) {if (op == '*') {result_ += (preNum * nextNum) + '';} else if (op == '/') {result_ += (preNum / nextNum) + '';} else if (op == '+') {result_ += (preNum + nextNum) + '';} else {result_ += (preNum - nextNum) + '';}}continue;}result_ += result.charAt(i);}return result_;}
}

18. src/process/PointProcess.ts

import BaseProcess from './BaseProcess';/*** 实现操作符的处理*/
export default class OpratorProcess implements BaseProcess {char: string;constructor(char_: string) {this.char = char_;}/*** .的处理* @param result * @returns 合并后的结果*/process(result: string): string {if (result.charAt(result.length - 1) == '.') {return result;}if (result.charAt(result.length - 1) == '+' || result.charAt(result.length - 1) == '-' || result.charAt(result.length - 1) == '*' || result.charAt(result.length - 1) == '/') {return result + '0.';}return result + '' + this.char;}
}

19. src/process/SqtProcess.ts

import BaseProcess from './BaseProcess';/*** 几分之几的处理*/
export default class SqtProcess implements BaseProcess {char: string;constructor(char_: string) {this.char = char_;}/*** 几分之几的处理* @param value 空值* @param result * @returns */process(result: string): string {/*** 计算结果:1+2-3/4*5*/while (result.indexOf('+') != -1 || result.indexOf('-') != -1 || result.indexOf('/') != -1 || result.indexOf('*') != -1) {//先计算乘除let chenIndex = result.indexOf('*');let chuIndex = result.indexOf('/');while (chenIndex >= 0 || chuIndex >= 0) {if (chenIndex >= 0 && chuIndex >= 0) {//有乘的计算、也有除的计算if (chenIndex < chuIndex) {//乘在前result = this.jisuan('*', result, chenIndex);} else {result = this.jisuan('/', result, chuIndex);}} else {if (chenIndex >= 0) {result = this.jisuan('*', result, chenIndex);} else if (chuIndex >= 0) {result = this.jisuan('/', result, chuIndex);}}chenIndex = result.indexOf('*');chuIndex = result.indexOf('/');}let jiaIndex = result.indexOf('+');let jianIndex = result.indexOf('-');if (jiaIndex >= 0 && jianIndex >= 0) {//计算加减if (jiaIndex < jianIndex) {result = this.jisuan('+', result, jiaIndex);} else {result = this.jisuan('-', result, jianIndex);}} else {if (jiaIndex >= 0) {result = this.jisuan('+', result, jiaIndex);} else if (jianIndex >= 0) {result = this.jisuan('-', result, jianIndex);}}}return Math.sqrt(parseFloat(result)) + '';}jisuan(op: string, result: string, index: number): string {let preStr = '';let startIndex = 0;for (let i = index - 1; i >= 0 && (result.charAt(i) !== '*' && result.charAt(i) !== '/' && result.charAt(i) !== '+' && result.charAt(i) !== '-'); i--) {preStr += result[i];startIndex = i;}//反转preStr = preStr.split('').reverse().join('');let nexStr = '';let endIndex = 0;for (let i = index + 1; i < result.length && (result.charAt(i) !== '*' && result.charAt(i) !== '/' && result.charAt(i) !== '+' && result.charAt(i) !== '-'); i++) {nexStr += result[i];endIndex = i;}let preNum = parseFloat(preStr);let nextNum = parseFloat(nexStr);let result_ = '';for (let i = 0; i < result.length; i++) {if (i >= startIndex && i <= endIndex) {if (i == startIndex) {if (op == '*') {result_ += (preNum * nextNum) + '';} else if (op == '/') {result_ += (preNum / nextNum) + '';} else if (op == '+') {result_ += (preNum + nextNum) + '';} else {result_ += (preNum - nextNum) + '';}}continue;}result_ += result.charAt(i);}return result_;}
}

六.遇到的问题

问题一: HTMLDivElement无法继承的问题。
  因为ts中HTMLDivElement是一个接口,没有声明类,因为是一个底层类型,不适合进行扩展。
 可以新建类实现一个此接口,但就需要实现所有的属性和接口的方法,不太显示;
 可以新建一个类,定义一个HTMLDivElement类型的数据,将需要封装的内容封装到新建的类中实现想要的效果;
 也可使用声明合并对HTMLDivElement进行扩展声明,实现相应的功能。
问题二: 直接给元素添加点击事件回调时,接口类型的问题。

相关文章:

TS项目实战二:网页计算器

使用ts实现网页计算器工具&#xff0c;实现计算器相关功能&#xff0c;使用tsify进行项目编译&#xff0c;引入Browserify实现web界面中直接使用模块加载服务。   源码下载&#xff1a;点击下载 讲解视频 TS实战项目四&#xff1a;计算器项目创建 TS实战项目五&#xff1a;B…...

MySQL的ACID、死锁、MVCC问题

1 ACID ACID代表原子性&#xff08;atomicity&#xff09;、一致性&#xff08;consistency&#xff09;、隔离性&#xff08;isolation&#xff09;和持久性&#xff08;durability&#xff09;。一个确保数据安全的事务处理系统&#xff0c;必须满足这些密切相关的标准。 原…...

Docker 可视化工具

1、Portainer 概念介绍 Portainer是一款轻量级的应用&#xff0c;它提供了图形化界面&#xff0c;用于方便地管理Docker环境&#xff0c;包括单机环境和集群环境。 Portainer分为开源社区版&#xff08;CE版&#xff09;和商用版&#xff08;BE版/EE版&#xff09;。 Porta…...

【C++】友元:友元函数与友元类

一、友元 友元&#xff08;friend&#xff09;是C中的一种特殊关系&#xff0c;用于在类之间共享访问权限。通过将一个函数或类声明为另一个类的友元&#xff0c;我们可以允许友元访问声明类的非公有成员。 二、友元函数 问题&#xff1a;现在尝试去重载operator<<&am…...

linux之wsl2安装远程桌面

0. 安装后的效果 1. wsl中打开terminal并安装库 sudo apt-get purge xrdp sudo apt install -y xrdp sudo apt install -y xfce4 sudo apt install -y xfce4-goodies 2.优化显示 sudo sed -i s/max_bpp32/#max_bpp32\nmax_bpp128/g /etc/xrdp/xrdp.ini sudo sed -i s/xserverbp…...

如何以管理员身份删除node_modules文件

今天拉项目&#xff0c;然后需要安装依赖&#xff0c;但是一直报错&#xff0c;如下&#xff1a; 去搜这个问题会让把node_modules文件先删掉 再去安装依赖。我在删除的过程中会说请以管理员身份来删除。 那么windows如何以管理员身份删除node_modules文件呢&#xff1f; wi…...

【Linux】环境基础开发工具的使用之gdb详解(三)

前言&#xff1a;上一篇文章中我们讲解了Linux下的gcc与g的使用&#xff0c;今天我们将进一步的学习gdb与makefile来帮我们更好的理解与使用基础开发工具。 &#x1f496; 博主CSDN主页:卫卫卫的个人主页 &#x1f49e; &#x1f449; 专栏分类:Linux的深度刨析 &#x1f448; …...

SpringBoot源码解读与原理分析(二十四)IOC容器的刷新(五)

文章目录 7.11 初始化所有剩下的单实例bean对象7.11.1 beanFactory.preInstantiateSingletons7.11.2 getBean7.11.2.1 别名的解析处理7.11.2.2 判断是否已注册过7.11.2.3 创建前的检查7.11.2.4 标记准备创建的bean对象7.11.2.5 合并BeanDefinition7.11.2.6 bean对象的创建7.11.…...

最大子数组和

一、题目 给你一个整数数组nums&#xff0c;请你找出一个具有最大和的连续子数组&#xff08;子数组最少包含一个元素&#xff09;&#xff0c;返回其最大和。子数组 是数组中的一个连续部分。 示例 1&#xff1a; 输入&#xff1a;nums [-2,1,-3,4,-1,2,1,-5,4] 输出&#…...

Node.js版本管理工具之_Volta

Node.js包管理工具之_Volta 文章目录 Node.js包管理工具之_Volta1. 官网1. 官网介绍2. 特点1. 快( Fast)2. 可靠(Reliable)3. 普遍( Universal) 2. 下载与安装1. 下载2. 安装3. 查看 3. 使用1. 查看已安装的工具包2. 安装指定的node版本3.切换项目中使用的版本 1. 官网 1. 官网…...

Redis 命令大全

文章目录 启动与连接Key&#xff08;键&#xff09;相关命令String&#xff08;字符串&#xff09;Hash&#xff08;哈希&#xff09;List&#xff08;列表&#xff09;Set&#xff08;集合&#xff09;Sorted Set&#xff08;有序集合&#xff09;其他常见命令HyperLogLog&…...

再这么烂下去,离糊就不远了。别让才华被埋没。

♥ 为方便您进行讨论和分享&#xff0c;同时也为能带给您不一样的参与感。请您在阅读本文之前&#xff0c;点击一下“关注”&#xff0c;非常感谢您的支持&#xff01; 文 |猴哥聊娱乐 编 辑|徐 婷 校 对|侯欢庭 近日&#xff0c;胡歌凭借电视剧《繁花》荣登《环球银幕》二月…...

Unity BuffSystem buff系统

Unity BuffSystem buff系统 一、介绍二、buff系统架构三、架构讲解四、框架使用buff数据Json数据以及工具ShowTypeBuffTypeMountTypeBuffOverlapBuffShutDownTypeBuffCalculateType时间和层数这里也不过多说明了如何给生物添加buff 五、总结 一、介绍 现在基本做游戏都会需要些…...

Android rom定制 修改system分区的容量大小

1、写在前面 系统ROM定制化,预置app太多,会导致系统rom很大,原生系统system分区已经不够用了,要加大系统systemui分区 2.修改system分区的容量大小的核心类 device/mediatekprojects/$project/BoardConfig.mk build/make/core/Makefile3、修改system 分区的容量大小的核…...

速盾:服务器接入免备案CDN节点的好处有哪些

本文将探讨服务器接入免备案CDN节点的好处&#xff0c;包括提高网站的访问速度、增加网站的稳定性和可靠性、降低带宽成本等方面的优势。同时&#xff0c;还将提供一些相关问题的解答&#xff0c;帮助读者更好地了解这一技术。 随着互联网的迅猛发展&#xff0c;网站的访问速度…...

Redisson看门狗机制

一、背景 网上redis分布式锁的工具方法&#xff0c;大都满足互斥、防止死锁的特性&#xff0c;有些工具方法会满足可重入特性。如果只满足上述3种特性会有哪些隐患呢&#xff1f;redis分布式锁无法自动续期&#xff0c;比如&#xff0c;一个锁设置了1分钟超时释放&#xff0c;…...

【Java数据结构】双向 不带头 非循环 链表实现(模拟实现LinkedList类)

LinkedList底层实际上是双向、不带头结点、非循环的链表 链表的分类有八种&#xff0c;常用的有两种&#xff1a;一是单向、不带头结点、非循环的&#xff08;基本上网上的题型都是这种&#xff09;&#xff1b;二是双向、不带头结点、非循环&#xff08;LinkedList的底层实现…...

深度学习系列55:深度学习加速技术概述

总体有两个方向&#xff1a;模型优化 / 框架优化 1. 模型优化 1.1 量化 最常见的量化方法为线性量化&#xff0c;权重从float32量化为int8&#xff0c;将输入数据映射在[-128,127]的范围内。在 nvdia gpu&#xff0c;x86、arm 和 部分 AI 芯片平台上&#xff0c;均支持 8bit…...

使用python启动一个roslaunch文件

roslaunch 的实现源码主要位于 ROS 的 ros_comm 仓库中的 tools/roslaunch 目录下。源码主要由 Python 脚本和少量的 C 代码组成。 在Python程序中导入roslaunch包并启动一个ROS launch文件&#xff0c;你需要确保ROS环境已经设置好&#xff0c;并且相关的roslaunch包已经安装…...

JavaEE企业级应用软件开发—Spring框架入门学习笔记(一)

一、认识框架 实际开发中&#xff0c;随着业务的发展&#xff0c;软件系统变得越来越复杂&#xff0c;如果所有的软件都从底层功能开始开发&#xff0c;那将是一个漫长而繁琐的过程。此外&#xff0c;团队协作开发时&#xff0c;由于没有统一的调用规范&#xff0c;系统会出现大…...

ElasticSearch-SpringBoot整合ElasticSearch

六、SpringBoot整合ElasticSearch 1、浏览官方文档 1、查找跟ES客户端相关的文档 使用Java REST Client 选择Java Hight Level REST Client 2、创建项目的准备 1.找到原生的依赖 2.找到对象 3.分析这个类里面的方法 3、正式创建项目 1.创建工程 2.导入依赖 注意依赖版本…...

用云手机打造tiktok账号需要注意些什么?

随着tiktok平台的火热&#xff0c;越来越多的商家开始尝试更高效的tiktok运营方法。其中&#xff0c;tiktok云手机作为一种新科技引起了很多人的注意&#xff0c;那么用云手机运营tiktok需要注意些什么&#xff1f;下文将对此进行详细解析。 1. 不是所有的云手机都适合做tiktok…...

MySQL基础查询篇(9)-数学函数在查询中的应用

在MySQL数据库中&#xff0c;数学函数在查询中扮演了非常重要的角色。这些函数可以帮助我们进行各种数学计算和处理&#xff0c;使得我们能够更有效地处理和分析数据。本文将介绍一些常用的MySQL数学函数及其在查询中的应用。 1. ABS函数 ABS函数用于返回一个数值的绝对值。在…...

c#内置委托

C#语言中有许多内置的委托&#xff0c;其中一些是常用的&#xff0c;包括&#xff1a; Action&#xff1a;表示不带返回值的方法的委托。它可以接受多个参数&#xff0c;但不返回任何值。 Action<int, string> actionDelegate (x, y) > Console.WriteLine("Ac…...

【自动化测试】---Selenium+Java

1.自动化测试分类 接口自动化测试UI自动化测试&#xff08;移动端自动化测试、Web端自动化测试&#xff09; 2.选择Selenium作为web自动化工具原因&#xff08;面试题&#xff09; 开源免费支持多个浏览器支持多个系统支持多语言Selenium包提供很多供测试使用的API 3.自动化是什…...

uniapp新增一条数据增加一个折叠栏

//折叠栏 <uni-collapse classcollapse refcollapse><uni-collapse-item v-for"(item, index) in dataForm.beefCattleNums" :key"index" :title"item.fatCalfNum" classcollapse-item title-bordershow :borderfalse clicktoggleItem(…...

【Netty技术专题】「原理分析系列」Netty强大特性之Native transports扩展开发实战

Netty强大特性之Native transports技术原理分析 背景介绍JNI概念介绍不同平台的JNI实现 使用Native transports库Maven的分类器&#xff08;Classifier&#xff09;使用Linux native transport使用MacOS/BSD native transport库构建native transport库Linux版本要求MacOS/BSD版…...

1-1 动手学深度学习v2-线性回归-笔记

简化核心模型 假设1: 影响房价的关键因素是卧室个数&#xff0c;卫生间个数和居住面积&#xff0c;记为 x 1 x_{1} x1​&#xff0c; x 2 x_{2} x2​&#xff0c; x 3 x_{3} x3​假设2: 成交价是关键因素的加权和 y w 1 x 1 w 2 x 2 w 3 x 3 b yw_{1}x_{1}w_{2}x_{2}w_{3…...

算法每日一题: 使用循环数组所有元素相等的最少秒数 | 哈希

大家好&#xff0c;我是星恒&#xff0c;今天给大家带来的是一道需要感觉规律的题目&#xff0c;只要读懂题目中的规律&#xff0c;就可以做出来了 这道题用到了哈希&#xff0c;还有一个关键点比较类似循环队列 题目&#xff1a;leetcode 2808 给你一个下标从 0 开始长度为 n…...

canvas实现涂鸦画板功能

查看专栏目录 canvas实例应用100专栏&#xff0c;提供canvas的基础知识&#xff0c;高级动画&#xff0c;相关应用扩展等信息。canvas作为html的一部分&#xff0c;是图像图标地图可视化的一个重要的基础&#xff0c;学好了canvas&#xff0c;在其他的一些应用上将会起到非常重…...