1035. Password (20)

本文介绍了一个简单的C++程序,该程序用于批量修改用户账户密码中特定字符。程序通过将'1'替换为'@','0'替换为'%','l'替换为'L','O'替换为'o'来增强密码的安全性,并统计了被修改的账户数量。
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <algorithm>

#include <cstring>

using namespace std;

struct node
{
    char name[25],pwd[25];
    bool ischange=false;//默认为没有被修改过
}T[1005];

int cou=0;
void modify(node &T)
{
    for(int i=0;i<strlen(T.pwd);i++)
    {
        if(T.pwd[i]=='1')
        {
            T.pwd[i]='@';
            T.ischange=true;
        }
        else if(T.pwd[i]=='0')
        {
            T.pwd[i]='%';
            T.ischange=true;
        }
        else if(T.pwd[i]=='l')
        {
            T.pwd[i]='L';
            T.ischange=true;
        }
        else if(T.pwd[i]=='O')
        {
            T.pwd[i]='o';
            T.ischange=true;
        }
    }
    if(T.ischange==true)
    {
        cou++;
    }
}
int main()
{
  //  freopen("in.txt","r",stdin);

    int N;
    scanf("%d",&N);
    for(int i=0;i<N;i++)
    {
        scanf("%s %s",T[i].name,T[i].pwd);
        modify(T[i]);
    }

    if(cou==0)
    {
        if(N==1)
            printf("There is 1 account and no account is modified\n");
        else
            printf("There are %d accounts and no account is modified",N);
    }
    else
    {
        printf("%d\n",cou);
        for(int i=0;i<N;i++)
        {
            if(T[i].ischange==true)
                printf("%s %s\n",T[i].name,T[i].pwd);
        }
    }



    return 0;
}

mysql> SHOW PROCESSLIST; +------+-----------------+--------------------+-------------+---------+---------+---------------------------------+----------------------------------- -------------------------------------------------------------------+ | Id | User | Host | db | Command | Time | State | Info | +------+-----------------+--------------------+-------------+---------+---------+---------------------------------+----------------------------------- -------------------------------------------------------------------+ | 5 | event_scheduler | localhost | NULL | Daemon | 1115058 | Waiting on empty queue | NULL | | 1366 | root | 192.168.11.5:49618 | gjxqmp | Killed | 54284 | waiting for handler commit | commit | | 1368 | root | 192.168.11.6:59556 | zdb | Query | 54273 | Waiting for table metadata lock | INSERT INTO QRTZ_FIRED_TRIGGERS (S CHED_NAME, ENTRY_ID, TRIGGER_NAME, TRIGGER_GROUP, INSTANCE_NAME, F | | 1371 | root | 192.168.11.6:59558 | zdb | Query | 54284 | waiting for handler commit | commit | | 1373 | root | 192.168.11.6:59562 | wzhy | Query | 54284 | waiting for handler commit | commit | | 1374 | root | 192.168.11.5:49624 | miniprogram | Query | 54283 | waiting for handler commit | commit | | 1375 | root | 192.168.11.6:59566 | wzhy | Query | 54269 | waiting for handler commit | commit | | 1376 | root | 192.168.11.6:59564 | bdb | Query | 54284 | waiting for handler commit | commit | | 1377 | root | 192.168.11.5:49626 | dzzzproxy | Query | 54284 | waiting for handler commit | commit | | 1378 | root | 192.168.11.6:59568 | gjxqmp | Killed | 54269 | waiting for handler commit | commit | | 1401 | root | localhost | zdb | Query | 54284 | Waiting for table metadata lock | LOCK TABLES `act_evt_log` READ /*! 32311 LOCAL */,`act_ge_bytearray` READ /*!32311 LOCAL */,`act_ge_p | | 1406 | root | 192.168.11.5:49632 | miniprogram | Sleep | 8 | | NULL | | 1417 | root | 192.168.11.6:59586 | zdb | Sleep | 1 | | NULL | | 1419 | root | 192.168.11.6:59588 | wzhy | Query | 15027 | waiting for handler commit | insert into sys_oper_log(title, bu siness_type, method, request_method, operator_type, oper_name, dep | | 1420 | root | 192.168.11.5:49644 | gjxqmp | Query | 21900 | waiting for handler commit | update sys_user SET dept_id = 428, login_name = 'shenpi', user_name = '行政审批局 | | 1424 | root | 192.168.11.5:49648 | gjxqmp | Query | 21900 | waiting for handler commit | insert into sys_logininfor (login_ name, status, ipaddr, login_location, browser, os, msg, login_time | | 1425 | root | 192.168.11.5:49650 | gjxqmp | Query | 18820 | waiting for handler commit | insert into ncx_file ( URL, O_FILE_NAME, CREATE_TIME ) va | | 1426 | root | 192.168.11.5:49652 | gjxqmp | Query | 18813 | waiting for handler commit | insert into ncx_file ( URL, O_FILE_NAME, CREATE_TIME ) va | | 1427 | root | 192.168.11.5:49654 | gjxqmp | Query | 18772 | waiting for handler commit | insert into ncx_file ( URL, O_FILE_NAME, CREATE_TIME ) va | | 1428 | root | 192.168.11.5:49656 | gjxqmp | Query | 18764 | waiting for handler commit | insert into ncx_file ( URL, O_FILE_NAME, CREATE_TIME ) va | | 1429 | root | 192.168.11.5:49658 | gjxqmp | Query | 18672 | waiting for handler commit | insert into ncx_file ( URL, O_FILE_NAME, CREATE_TIME ) va | | 1430 | root | 192.168.11.5:49660 | gjxqmp | Query | 18670 | waiting for handler commit | insert into ncx_file ( URL, O_FILE_NAME, CREATE_TIME ) va | | 1431 | root | 192.168.11.5:49662 | gjxqmp | Query | 18614 | waiting for handler commit | insert into ncx_file ( URL, O_FILE_NAME, CREATE_TIME ) va | | 1432 | root | 192.168.11.5:49664 | gjxqmp | Query | 18614 | waiting for handler commit | insert into ncx_file ( URL, O_FILE_NAME, CREATE_TIME ) va | | 1433 | root | 192.168.11.5:49666 | gjxqmp | Query | 18519 | waiting for handler commit | insert into ncx_file ( URL, O_FILE_NAME, CREATE_TIME ) va | | 1434 | root | 192.168.11.5:49668 | gjxqmp | Query | 18519 | waiting for handler commit | insert into ncx_file ( URL, O_FILE_NAME, CREATE_TIME ) va | | 1435 | root | 192.168.11.5:49670 | gjxqmp | Query | 13482 | waiting for handler commit | insert into ncx_file ( URL, O_FILE_NAME, CREATE_TIME ) va | | 1436 | root | 192.168.11.5:49672 | gjxqmp | Query | 16386 | waiting for handler commit | insert into sys_logininfor (login_ name, status, ipaddr, login_location, browser, os, msg, login_time | | 1438 | root | 192.168.11.6:59594 | wzhy | Query | 15014 | waiting for handler commit | insert into sys_oper_log(title, bu siness_type, method, request_method, operator_type, oper_name, dep | | 1441 | root | 192.168.11.5:49676 | gjxqmp | Query | 13482 | waiting for handler commit | insert into ncx_file ( URL, O_FILE_NAME, CREATE_TIME ) va | | 1442 | root | 192.168.11.5:49678 | gjxqmp | Query | 13450 | waiting for handler commit | insert into ncx_file ( URL, O_FILE_NAME, CREATE_TIME ) va | | 1443 | root | 192.168.11.5:49680 | gjxqmp | Query | 13450 | waiting for handler commit | insert into ncx_file ( URL, O_FILE_NAME, CREATE_TIME ) va | | 1444 | root | 192.168.11.5:49682 | gjxqmp | Query | 13431 | waiting for handler commit | insert into ncx_file ( URL, O_FILE_NAME, CREATE_TIME ) va | | 1445 | root | 192.168.11.5:49684 | gjxqmp | Query | 13430 | waiting for handler commit | insert into ncx_file ( URL, O_FILE_NAME, CREATE_TIME ) va | | 1446 | root | 192.168.11.6:59600 | bdb | Sleep | 0 | | NULL | | 1448 | root | 192.168.11.6:59604 | wzhy | Sleep | 1 | | NULL | | 1450 | root | 192.168.11.5:49688 | gjxqmp | Killed | 3572 | waiting for handler commit | DELETE FROM QRTZ_CRON_TRIGGERS WHE RE SCHED_NAME = 'RuoyiScheduler' | | 1459 | root | 192.168.11.5:49706 | dzzzproxy | Sleep | 5 | | NULL | | 1465 | root | 192.168.11.6:59606 | gjxqmp | Sleep | 1 | | NULL | | 1472 | root | localhost | NULL | Query | 0 | init | SHOW PROCESSLIST | | 1473 | root | 192.168.11.6:59608 | wzhy | Sleep | 1 | | NULL | | 1474 | root | 192.168.11.6:59610 | gjxqmp | Query | 17 | updating | UPDATE QRTZ_SCHEDULER_STATE SET LAST_CHECKIN_TIME = 1747724644872 WHERE SCHED_NAME = 'RuoyiScheduler | +------+-----------------+--------------------+-------------+---------+---------+---------------------------------+------------------------------------------------------------------------------------------------------+ 42 rows in set (0.00 sec) mysql> 这个gjxqmq是项目启动连接的数据库 但是现在项目启动报错gAsyncExecutor]. 15:03:27.326 [activiti-acquire-async-jobs] INFO o.a.e.i.a.AcquireAsyncJobsDueRunnable - [run,115] - {} stopped async job due acquisition 15:03:27.326 [activiti-acquire-timer-jobs] INFO o.a.e.i.a.AcquireTimerJobsRunnable - [run,115] - {} stopped async job due acquisition 15:03:27.326 [activiti-reset-expired-jobs] INFO o.a.e.i.a.ResetExpiredJobsRunnable - [run,99] - {} stopped resetting expired jobs Tue May 20 15:03:27 CST 2025 WARN: Caught while disconnecting... EXCEPTION STACK TRACE: ** BEGIN NESTED EXCEPTION ** javax.net.ssl.SSLException MESSAGE: closing inbound before receiving peer's close_notify STACKTRACE: javax.net.ssl.SSLException: closing inbound before receiving peer's close_notify at sun.security.ssl.SSLSocketImpl.shutdownInput(SSLSocketImpl.java:740) at sun.security.ssl.SSLSocketImpl.shutdownInput(SSLSocketImpl.java:719) at com.mysql.cj.protocol.a.NativeProtocol.quit(NativeProtocol.java:1312) at com.mysql.cj.NativeSession.quit(NativeSession.java:182) at com.mysql.cj.jdbc.ConnectionImpl.realClose(ConnectionImpl.java:1750) at com.mysql.cj.jdbc.ConnectionImpl.close(ConnectionImpl.java:720) at com.alibaba.druid.pool.DruidDataSource.close(DruidDataSource.java:1903) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:498) at org.springframework.beans.factory.support.DisposableBeanAdapter.invokeCustomDestroyMethod(DisposableBeanAdapter.java:337) at org.springframework.beans.factory.support.DisposableBeanAdapter.destroy(DisposableBeanAdapter.java:271) at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.destroyBean(DefaultSingletonBeanRegistry.java:571) at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.destroySingleton(DefaultSingletonBeanRegistry.java:543) at org.springframework.beans.factory.support.DefaultListableBeanFactory.destroySingleton(DefaultListableBeanFactory.java:1052) at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.destroySingletons(DefaultSingletonBeanRegistry.java:504) at org.springframework.beans.factory.support.DefaultListableBeanFactory.destroySingletons(DefaultListableBeanFactory.java:1059) at org.springframework.context.support.AbstractApplicationContext.destroyBeans(AbstractApplicationContext.java:1035) at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:559) at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:142) at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:775) at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:397) at org.springframework.boot.SpringApplication.run(SpringApplication.java:316) at org.springframework.boot.SpringApplication.run(SpringApplication.java:1260) at org.springframework.boot.SpringApplication.run(SpringApplication.java:1248) at com.ruoyi.RuoYiApplication.main(RuoYiApplication.java:23) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:498) at org.springframework.boot.loader.MainMethodRunner.run(MainMethodRunner.java:48) at org.springframework.boot.loader.Launcher.launch(Launcher.java:87) at org.springframework.boot.loader.Launcher.launch(Launcher.java:50) at org.springframework.boot.loader.JarLauncher.main(JarLauncher.java:51)
05-21
PS F:\Programmer\python\new_my_AI> cd backend PS F:\Programmer\python\new_my_AI\backend> ls 目录: F:\Programmer\python\new_my_AI\backend Mode LastWriteTime Length Name ---- ------------- ------ ---- d----- 2025/11/5 17:53 models d----- 2025/11/6 9:59 routers d----- 2025/11/5 18:36 schemas -a---- 2025/11/5 17:59 325 .env -a---- 2025/11/5 17:58 888 config.py -a---- 2025/11/5 17:54 1035 database.py -a---- 2025/11/5 17:39 540 dependencies.py -a---- 2025/10/19 19:45 1838 install_deps.bat -a---- 2025/11/5 17:57 4108 jwt_handler.py -a---- 2025/11/5 17:16 1280 logger_setup.py -a---- 2025/11/5 17:45 1023 main.py -a---- 2025/10/19 18:58 283 requirements.txt PS F:\Programmer\python\new_my_AI\backend> cd models PS F:\Programmer\python\new_my_AI\backend\models> ls 目录: F:\Programmer\python\new_my_AI\backend\models Mode LastWriteTime Length Name ---- ------------- ------ ---- -a---- 2025/11/5 17:53 1978 chat.py -a---- 2025/11/5 17:51 733 department.py -a---- 2025/11/5 17:52 2417 post.py -a---- 2025/11/5 17:53 398 search.py -a---- 2025/11/5 17:51 1378 user.py -a---- 2025/11/5 17:50 544 __init__.py PS F:\Programmer\python\new_my_AI\backend\models> cd .. PS F:\Programmer\python\new_my_AI\backend> cd routers PS F:\Programmer\python\new_my_AI\backend\routers> ls 目录: F:\Programmer\python\new_my_AI\backend\routers Mode LastWriteTime Length Name ---- ------------- ------ ---- -a---- 2025/11/5 17:20 2979 api_chat.py -a---- 2025/11/5 17:43 1447 auth.py -a---- 2025/11/5 17:45 1677 chat_rooms.py -a---- 2025/11/5 17:44 2349 comments.py -a---- 2025/11/5 17:44 1097 departments.py -a---- 2025/11/5 17:47 751 posts.py -a---- 2025/11/5 17:45 1602 search.py -a---- 2025/11/6 9:59 0 __init__.py PS F:\Programmer\python\new_my_AI\backend\routers> cd .. PS F:\Programmer\python\new_my_AI\backend> cd schemas PS F:\Programmer\python\new_my_AI\backend\schemas> ls 目录: F:\Programmer\python\new_my_AI\backend\schemas Mode LastWriteTime Length Name ---- ------------- ------ ---- -a---- 2025/11/5 18:03 435 auth.py -a---- 2025/11/5 18:02 951 chat.py -a---- 2025/11/5 18:01 587 comment.py -a---- 2025/11/5 18:36 3777 common.py -a---- 2025/11/5 17:42 481 post.py -a---- 2025/11/5 17:41 100 user.py PS F:\Programmer\python\new_my_AI\backend\schemas> 这是我现在的项目结构 # backend/database.py from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession, async_sessionmaker from sqlmodel import SQLModel from contextlib import asynccontextmanager from config import settings import asyncio # 从 models 包导入所有表模型 from models import * # 创建引擎 engine = create_async_engine( settings.DATABASE_URL, echo=settings.DEBUG, pool_pre_ping=True ) AsyncSessionLocal = async_sessionmaker( bind=engine, class_=AsyncSession, expire_on_commit=False ) @asynccontextmanager async def get_db(): async with AsyncSessionLocal() as session: try: yield session await session.commit() except Exception: await session.rollback() raise async def create_tables(): async with engine.begin() as conn: await conn.run_sync(SQLModel.metadata.create_all) print("✅ 所有数据库表已创建完成!") async def close_db(): await engine.dispose() # backend/dependencies.py from fastapi import Depends, HTTPException from sqlalchemy import select from database import User, get_db from jwt_handler import get_current_user_id async def get_current_active_user(user_id: str = Depends(get_current_user_id)): async with get_db() as db: result = await db.execute(select(User).where(User.id == int(user_id))) user = result.scalar_one_or_none() if not user: raise HTTPException(status_code=404, detail="用户不存在") return user # backend/jwt_handler.py from datetime import datetime, timedelta, timezone from pathlib import Path from typing import Optional import os from dotenv import load_dotenv from fastapi import Cookie, Depends, HTTPException from jose import jwt, JWTError from passlib.hash import pbkdf2_sha256 from pydantic import BaseModel from config import settings # 使用统一配置 from logger_setup import app_logger as logger # ==================== 模型定义 ==================== class TokenData(BaseModel): user_id: Optional[str] = None # ==================== 密码工具 ==================== def get_password_hash(password: str) -> str: """ 使用 PBKDF2-SHA256 对密码进行哈希。 默认 rounds=29000,安全性高,适合用户密码存储。 """ return pbkdf2_sha256.hash(password) def verify_password(plain_password: str, hashed_password: str) -> bool: """ 校验明文密码是否匹配哈希值。 Passlib 会自动识别 salt 和 rounds。 """ return pbkdf2_sha256.verify(plain_password, hashed_password) # ==================== JWT 工具函数 ==================== def create_access_token(data: dict, expires_delta: Optional[timedelta] = None) -> str: """ 创建 JWT 访问令牌 :param data: 要编码的数据,建议包含 {"sub": "user_id"} :param expires_delta: 可选的过期时间偏移量 :return: 编码后的 JWT 字符串 """ to_encode = data.copy() expire = datetime.now(timezone.utc) + ( expires_delta if expires_delta else timedelta(minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES) ) to_encode.update({"exp": expire}) encoded_jwt = jwt.encode(to_encode, settings.SECRET_KEY, algorithm=settings.ALGORITHM) logger.info(f"✅ JWT 已生成,有效期至: {expire}") return encoded_jwt def decode_access_token(token: str) -> Optional[dict]: """ 【同步】解码 JWT 并返回 payload(可用于中间件、日志等非 await 上下文) :param token: JWT 字符串 :return: 解码后的 payload 或 None(无效/过期) """ try: payload = jwt.decode(token, settings.SECRET_KEY, algorithms=[settings.ALGORITHM]) logger.debug(f"🔍 JWT 成功解码: {payload}") return payload except JWTError as e: logger.warning(f"❌ JWT 解码失败 (JWTError): {e}") return None except Exception as e: logger.error(f"❌ 意外错误解码 JWT: {e}") return None # ==================== FastAPI 依赖项 ==================== async def get_current_user_id(access_token: str = Cookie(None)) -> str: """ FastAPI 依赖:从 HttpOnly Cookie 提取用户 ID 若未登录或 token 无效,抛出 401 错误 :return: 用户 ID(字符串) """ if not access_token: logger.warning("🚫 请求缺少 access_token") raise HTTPException(status_code=401, detail="未登录") payload = decode_access_token(access_token) if not payload: logger.warning("⚠️ 无法解析 JWT payload") raise HTTPException(status_code=401, detail="凭证无效") user_id: str = payload.get("sub") if not user_id: logger.warning("⚠️ JWT 中缺少 'sub' 字段") raise HTTPException(status_code=401, detail="凭证不完整") logger.info(f"👤 当前用户已认证: user_id={user_id}") return user_id async def get_current_active_user(user_id: str = Depends(get_current_user_id)): """ 扩展依赖:根据 user_id 查询数据库中的活跃用户对象 (可在此处添加封禁检查、角色权限判断等) """ from database import get_user_by_id user = await get_user_by_id(int(user_id)) if not user: logger.warning(f"❌ 用户不存在: user_id={user_id}") raise HTTPException(status_code=404, detail="用户不存在") if user.role == "banned": raise HTTPException(status_code=403, detail="该账户已被封禁") return user # backend/logger_setup.py import logging import os from logging.handlers import RotatingFileHandler, TimedRotatingFileHandler from pathlib import Path from config import BASE_DIR LOG_DIR = BASE_DIR.parent / "logs" LOG_DIR.mkdir(exist_ok=True) def setup_logger(): logger = logging.getLogger("chat_app") logger.setLevel(logging.INFO) # 防止重复添加 handler if logger.handlers: return logger # 格式 formatter = logging.Formatter( '%(asctime)s | %(levelname)s | %(name)s | %(funcName)s() | %(message)s', datefmt='%Y-%m-%d %H:%M:%S' ) # 1. 按时间切割的日志文件(每天一个) file_handler = TimedRotatingFileHandler( LOG_DIR / "app.log", when="midnight", interval=1, backupCount=7, # 保留最近7天 encoding='utf-8' ) file_handler.setFormatter(formatter) file_handler.setLevel(logging.INFO) # 2. 控制台输出 console_handler = logging.StreamHandler() console_handler.setFormatter(formatter) console_handler.setLevel(logging.INFO) # 添加到 logger logger.addHandler(file_handler) logger.addHandler(console_handler) return logger app_logger = setup_logger() # backend/main.py from fastapi import FastAPI from fastapi.staticfiles import StaticFiles from config import FRONTEND_DIR from logger_setup import app_logger as logger from routers import auth, posts, comments, departments, search, chat_rooms app = FastAPI(title="AI社交平台", version="1.0") @app.middleware("http") async def log_requests(request, call_next): logger.info(f"➡️ {request.method} {request.url.path} | IP: {request.client.host}") response = await call_next(request) logger.info(f"⬅️ Status: {response.status_code}") return response app.mount("/static", StaticFiles(directory=str(FRONTEND_DIR / "static")), name="static") app.include_router(auth.router) app.include_router(posts.router) app.include_router(comments.router) app.include_router(departments.router) app.include_router(search.router) app.include_router(chat_rooms.router) if __name__ == "__main__": import uvicorn uvicorn.run("main:app", host="127.0.0.1", port=8000, reload=True) 整理一下,把缺失的部补全
11-07
### ArkTS中 `this.password == ''` 与 `this.password == null` 的区别 在 ArkTS 中,`this.password == ''` 和 `this.password == null` 并不等价。以下是两者之间的具体区别: #### 1. 空字符串 (`''`) 的含义 当比较 `this.password == ''` 时,表示检查变量 `password` 是否是一个空字符串。空字符串是一个有效的字符串值,意味着变量已被初始化为一个字符串类型,并且其内容为空[^1]。 ```typescript @State password: string = ''; // 初始化为一个空字符串 if (this.password == '') { console.log('Password is an empty string'); } ``` #### 2. `null` 的含义 `null` 是一个特殊的值,表示“无值”或“空值”。它通常用于表示变量未指向任何对象或值。如果 `this.password == null`,则表示变量 `password` 当前没有被赋值为任何有效的内容。 需要注意的是,在 JavaScript/TypeScript 的宽松相等比较 (`==`) 中,`null` 只等于自身和 `undefined`,而不会等于空字符串或其他值。 ```typescript @State password: string | null = null; // 初始化为 null if (this.password == null) { console.log('Password is null or undefined'); } ``` #### 3. 宽松相等 (`==`) 的行为 在 JavaScript/TypeScript 中,`==` 运算符会尝试进行类型转换后再比较值。以下是相关的规则: - 空字符串 (`''`) 不等于 `null` 或 `undefined`。 - `null` 等于 `undefined`,但不等于其他任何值。 - 如果一方是 `null` 或 `undefined`,另一方是非布尔值,则结果始终为 `false`。 因此,在 ArkTS 中: - `this.password == ''` 表示检查是否为一个空字符串。 - `this.password == null` 表示检查是否为 `null` 或 `undefined`。 #### 示例代码 以下代码展示了两者的差异: ```typescript @Entry @Component struct Test { @State password: string | null = ''; build() { Column() { Text(`Password is ${this.password}`) .fontSize(20) Button('Check Empty String') .onClick(() => { if (this.password == '') { console.log('Password is an empty string'); } else { console.log('Password is not an empty string'); } }) Button('Check Null') .onClick(() => { if (this.password == null) { console.log('Password is null or undefined'); } else { console.log('Password is not null or undefined'); } }) } .width('100%') .height('100%') .padding(20) } } ``` #### 总结 - `this.password == ''` 检查的是变量是否为一个空字符串。 - `this.password == null` 检查的是变量是否为 `null` 或 `undefined`。 - 在实际开发中,建议使用严格相等运算符 (`===`) 来避免隐式的类型转换问题[^1]。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值