ES6 字符串、数值、数组扩展使用总结

news2026/2/7 16:32:47

1. 字符串的扩展方法

1.1 includes()

// 判断字符串是否包含指定字符串
const str = 'Hello World';
console.log(str.includes('Hello')); // true
console.log(str.includes('hello')); // false
console.log(str.includes('World', 6)); // true - 从位置6开始搜索

// 实际应用
function validateEmail(email) {
  return email.includes('@') && email.includes('.');
}

1.2 startsWith()

// 判断字符串是否以指定字符串开头
const url = 'https://example.com';
console.log(url.startsWith('https')); // true
console.log(url.startsWith('http')); // false
console.log(url.startsWith('example', 8)); // true - 从位置8开始检查

// 实际应用
function isSecureUrl(url) {
  return url.startsWith('https://');
}

1.3 endsWith()

// 判断字符串是否以指定字符串结尾
const filename = 'document.pdf';
console.log(filename.endsWith('.pdf')); // true
console.log(filename.endsWith('.doc')); // false
console.log(filename.endsWith('ment', 8)); // true - 检查前8个字符

// 实际应用
function isImageFile(filename) {
  return filename.endsWith('.jpg') || filename.endsWith('.png');
}

1.4 repeat()

// 重复字符串指定次数
const star = '*';
console.log(star.repeat(5)); // '*****'

// 实际应用:创建缩进
function createIndent(level) {
  return ' '.repeat(level * 2);
}

// 创建进度条
function createProgressBar(progress) {
  const filled = '█'.repeat(progress);
  const empty = '░'.repeat(10 - progress);
  return filled + empty;
}
console.log(createProgressBar(3)); // '███░░░░░░░'

2. 数值的扩展

2.1 进制表示法

// 二进制表示法(0b 或 0B 开头)
const binary = 0b1010; // 10
console.log(binary);

// 八进制表示法(0o 或 0O 开头)
const octal = 0o744; // 484
console.log(octal);

// 实际应用:位运算
const permission = 0b111; // 读(4)写(2)执行(1)权限
const canRead = (permission & 0b100) === 0b100;    // true
const canWrite = (permission & 0b010) === 0b010;   // true
const canExecute = (permission & 0b001) === 0b001; // true

2.2 Number 新增方法

2.2.1 Number.isFinite()
// 检查一个数值是否有限
console.log(Number.isFinite(1)); // true
console.log(Number.isFinite(Infinity)); // false
console.log(Number.isFinite(-Infinity)); // false
console.log(Number.isFinite(NaN)); // false
console.log(Number.isFinite('15')); // false - 不会进行类型转换

// 实际应用
function validateInput(value) {
  return Number.isFinite(value) ? value : 0;
}
2.2.2 Number.isNaN()
// 检查一个值是否为 NaN
console.log(Number.isNaN(NaN)); // true
console.log(Number.isNaN(1)); // false
console.log(Number.isNaN('NaN')); // false - 不会进行类型转换

// 实际应用
function safeCalculation(x, y) {
  const result = x / y;
  return Number.isNaN(result) ? 0 : result;
}
2.2.3 Number.isInteger()
// 判断一个数值是否为整数
console.log(Number.isInteger(1)); // true
console.log(Number.isInteger(1.0)); // true
console.log(Number.isInteger(1.1)); // false

// 实际应用
function validateAge(age) {
  return Number.isInteger(age) && age >= 0;
}
2.2.4 Number.EPSILON
// 表示最小精度
console.log(Number.EPSILON); // 2.220446049250313e-16

// 实际应用:浮点数比较
function nearlyEqual(a, b) {
  return Math.abs(a - b) < Number.EPSILON;
}

console.log(nearlyEqual(0.1 + 0.2, 0.3)); // true,通常用来比较两个数是否相等

2.3 Math 新增方法

2.3.1 Math.trunc() 去除小数部分,不管大小直接抹掉小数部分
// 去除小数部分
console.log(Math.trunc(4.9)); // 4
console.log(Math.trunc(-4.1)); // -4
console.log(Math.trunc(-0.1234)); // 0

// 实际应用
function getHours(hours) {
  return Math.trunc(hours); // 去除小数部分的小时数
}
2.3.2 Math.sign()
// 判断一个数的符号
console.log(Math.sign(5)); // 1
console.log(Math.sign(-5)); // -1
console.log(Math.sign(0)); // 0
console.log(Math.sign(-0)); // -0
console.log(Math.sign(NaN)); // NaN

// 实际应用
function getTemperatureStatus(temp) {
  switch (Math.sign(temp)) {
    case 1: return '温度高于零度';
    case -1: return '温度低于零度';
    case 0: return '温度为零度';
    default: return '无效温度';
  }
}

3. 数组的扩展

3.1 扩展运算符

// 数组浅复制
const original = [1, 2, 3];
const copy = [...original];
console.log(copy); // [1, 2, 3]

// 数组合并
const arr1 = [1, 2];
const arr2 = [3, 4];
const combined = [...arr1, ...arr2];
console.log(combined); // [1, 2, 3, 4]

// 解构使用
const [first, ...rest] = [1, 2, 3, 4];
console.log(first); // 1
console.log(rest); // [2, 3, 4]

// 实际应用:函数参数
function sum(...numbers) {
  return numbers.reduce((total, num) => total + num, 0);
}
console.log(sum(1, 2, 3)); // 6

3.2 Array.from()

// 将类数组对象转换为数组
const arrayLike = { 0: 'a', 1: 'b', 2: 'c', length: 3 };
const array = Array.from(arrayLike);
console.log(array); // ['a', 'b', 'c']

// 转换 Set
const set = new Set([1, 2, 3]);
const arrayFromSet = Array.from(set);
console.log(arrayFromSet); // [1, 2, 3]

// 带映射函数
const mapped = Array.from([1, 2, 3], x => x * 2);
console.log(mapped); // [2, 4, 6]

// 实际应用:DOM 操作
const links = Array.from(document.querySelectorAll('a'));
const urls = links.map(link => link.href);

3.3 Array.of()

// 创建新数组
console.log(Array.of(1)); // [1]
console.log(Array.of(1, 2, 3)); // [1, 2, 3]
console.log(Array.of(undefined)); // [undefined]

// 对比 Array 构造函数
console.log(new Array(3)); // [empty × 3]
console.log(Array.of(3)); // [3]

// 实际应用
function createMatrix(rows, cols, value) {
  return Array.from({ length: rows }, () => Array.of(...Array(cols).fill(value)));
}
console.log(createMatrix(2, 2, 0)); // [[0, 0], [0, 0]]

3.4 查找方法

3.4.1 find() 和 findIndex()
const numbers = [1, 2, 3, 4, 5];

// find() - 返回第一个满足条件的元素
const found = numbers.find(num => num > 3);
console.log(found); // 4

// findIndex() - 返回第一个满足条件的元素的索引
const foundIndex = numbers.findIndex(num => num > 3);
console.log(foundIndex); // 3

// 实际应用
const users = [
  { id: 1, name: 'John' },
  { id: 2, name: 'Jane' }
];

const user = users.find(user => user.id === 2);
console.log(user); // { id: 2, name: 'Jane' }
3.4.2 findLast() 和 findLastIndex() 扁平化数组
const numbers = [1, 2, 3, 4, 5, 4, 3, 2, 1];

// findLast() - 从后向前查找第一个满足条件的元素
const lastFound = numbers.findLast(num => num > 3);
console.log(lastFound); // 4

// findLastIndex() - 从后向前查找第一个满足条件的元素的索引
const lastFoundIndex = numbers.findLastIndex(num => num > 3);
console.log(lastFoundIndex); // 5

// 实际应用
const transactions = [
  { id: 1, amount: 100 },
  { id: 2, amount: 200 },
  { id: 3, amount: 300 }
];

const lastLargeTransaction = transactions.findLast(t => t.amount > 150);
console.log(lastLargeTransaction); // { id: 3, amount: 300 }

3.5 fill()

// 用固定值填充数组
const array = new Array(3).fill(0);
console.log(array); // [0, 0, 0]

// 指定填充范围
const numbers = [1, 2, 3, 4, 5];
numbers.fill(0, 2, 4); // 从索引2到4(不包含)填充0
console.log(numbers); // [1, 2, 0, 0, 5]

// 实际应用:初始化矩阵
function createMatrix(rows, cols) {
  return Array(rows).fill().map(() => Array(cols).fill(0));
}
console.log(createMatrix(2, 3)); // [[0, 0, 0], [0, 0, 0]]

3.6 flat() 和 flatMap()

// flat() - 展平嵌套数组
const nested = [1, [2, 3], [4, [5, 6]]];
console.log(nested.flat()); // [1, 2, 3, 4, [5, 6]]
console.log(nested.flat(2)); // [1, 2, 3, 4, 5, 6]

// flatMap() - 映射并展平
const sentences = ['Hello world', 'Good morning'];
const words = sentences.flatMap(s => s.split(' '));
console.log(words); // ['Hello', 'world', 'Good', 'morning']

// 实际应用:数据处理
const orders = [
  { products: ['apple', 'banana'] },
  { products: ['orange'] }
];

const allProducts = orders.flatMap(order => order.products);
console.log(allProducts); // ['apple', 'banana', 'orange']

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2294072.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

如何利用maven更优雅的打包

最近在客户现场部署项目&#xff0c;有两套环境&#xff0c;无法连接互联网&#xff0c;两套环境之间也是完全隔离&#xff0c;于是问题就来了&#xff0c;每次都要远程到公司电脑改完代码&#xff0c;打包&#xff0c;通过网盘&#xff08;如果没有会员&#xff0c;上传下载慢…

图像分类与目标检测算法

在计算机视觉领域&#xff0c;图像分类与目标检测是两项至关重要的技术。它们通过对图像进行深入解析和理解&#xff0c;为各种应用场景提供了强大的支持。本文将详细介绍这两项技术的算法原理、技术进展以及当前的落地应用。 一、图像分类算法 图像分类是指将输入的图像划分为…

HAL库 Systick定时器 基于STM32F103EZT6 野火霸道,可做参考

目录 1.时钟选择(这里选择高速外部时钟) ​编辑 2.调试模式和时基源选择: 3.LED的GPIO配置 这里用板子的红灯PB5 4.工程配置 5.1ms的systick中断实现led闪烁 源码: 6.修改systick的中断频率 7.systick定时原理 SysTick 定时器的工作原理 中断触发机制 HAL_SYSTICK_Co…

Spring Boot常用注解深度解析:从入门到精通

今天&#xff0c;这篇文章带你将深入理解Spring Boot中30常用注解&#xff0c;通过代码示例和关系图&#xff0c;帮助你彻底掌握Spring核心注解的使用场景和内在联系。 一、启动类与核心注解 1.1 SpringBootApplication 组合注解&#xff1a; SpringBootApplication Confi…

【基于SprintBoot+Mybatis+Mysql】电脑商城项目之用户注册

&#x1f9f8;安清h&#xff1a;个人主页 &#x1f3a5;个人专栏&#xff1a;【计算机网络】【Mybatis篇】 &#x1f6a6;作者简介&#xff1a;一个有趣爱睡觉的intp&#xff0c;期待和更多人分享自己所学知识的真诚大学生。 目录 &#x1f3af;项目基本介绍 &#x1f6a6;项…

力扣1022. 从根到叶的二进制数之和(二叉树的遍历思想解决)

Problem: 1022. 从根到叶的二进制数之和 文章目录 题目描述思路复杂度Code 题目描述 思路 遍历思想(利用二叉树的先序遍历) 1.在先序遍历的过程中&#xff0c;用一个变量path记录并更新其经过的路径上的值&#xff0c;当遇到根节点时再将其加到结果值res上&#xff1b; 2.该题…

Redis背景介绍

⭐️前言⭐️ 本文主要做Redis相关背景介绍&#xff0c;包括核心能力、重要特性和使用场景。 &#x1f349;欢迎点赞 &#x1f44d; 收藏 ⭐留言评论 &#x1f349;博主将持续更新学习记录收获&#xff0c;友友们有任何问题可以在评论区留言 &#x1f349;博客中涉及源码及博主…

LabVIEW图像采集与应变场测量系统

开发了一种基于LabVIEW的图像采集与应变场测量系统&#xff0c;提供一种高精度、非接触式的测量技术&#xff0c;用于监测物体的全场位移和应变。系统整合了实时监控、数据记录和自动对焦等功能&#xff0c;适用于工程应用和科学研究。 项目背景 传统的位移和应变测量技术往往…

html基本结构和常见元素

html5文档基本结构 <!DOCTYPE html> <html lang"zh-CN"> <head><meta charset"UTF-8"><title>文档标题</title> </head> <body>文档正文部分 </body> </html> html文档可分为文档头和文档体…

upload labs靶场

upload labs靶场 注意:本人关卡后面似乎相比正常的关卡少了一关&#xff0c;所以每次关卡名字都是1才可以和正常关卡在同一关 一.个人信息 个人名称&#xff1a;张嘉玮 二.解题情况 三.解题过程 题目&#xff1a;up load labs靶场 pass 1前后端 思路及解题&#xff1a;…

手写MVVM框架-环境搭建

项目使用 webpack 进行进行构建&#xff0c;初始化步骤如下: 1.创建npm项目执行npm init 一直下一步就行 2.安装webpack、webpack-cli、webpack-dev-server&#xff0c;html-webpack-plugin npm i -D webpack webpack-cli webpack-dev-server html-webpack-plugin 3.配置webpac…

论文阅读:Realistic Noise Synthesis with Diffusion Models

这篇文章是 2025 AAAI 的一篇工作&#xff0c;主要介绍的是用扩散模型实现对真实噪声的仿真模拟 Abstract 深度去噪模型需要大量来自现实世界的训练数据&#xff0c;而获取这些数据颇具挑战性。当前的噪声合成技术难以准确模拟复杂的噪声分布。我们提出一种新颖的逼真噪声合成…

JVM监控和管理工具

基础故障处理工具 jps jps(JVM Process Status Tool)&#xff1a;Java虚拟机进程状态工具 功能 1&#xff1a;列出正在运行的虚拟机进程 2&#xff1a;显示虚拟机执行主类(main()方法所在的类) 3&#xff1a;显示进程ID(PID&#xff0c;Process Identifier) 命令格式 jps […

【TensorFlow】T1:实现mnist手写数字识别

&#x1f368; 本文为&#x1f517;365天深度学习训练营 中的学习记录博客&#x1f356; 原作者&#xff1a;K同学啊 1、设置GPU import tensorflow as tf gpus tf.config.list_physical_devices("GPU")if gpus:gpu0 gpus[0]tf.config.experimental.set_memory_g…

【ArcGIS_Python】使用arcpy脚本将shape数据转换为三维白膜数据

说明&#xff1a; 该专栏之前的文章中python脚本使用的是ArcMap10.6自带的arcpy&#xff08;好几年前的文章&#xff09;&#xff0c;从本篇开始使用的是ArcGIS Pro 3.3.2版本自带的arcpy&#xff0c;需要注意不同版本对应的arcpy函数是存在差异的 数据准备&#xff1a;准备一…

动静态库的学习

动静态库中&#xff0c;不需要包含main函数 文件分为内存级(被打开的)文件和磁盘级文件 库 每个程序都要依赖很多基础的底层库&#xff0c;本质上来说库是一种可执行代码的二进制形式&#xff0c;可以被载入内存执行 静态库 linux .a windows .lib 动态库 linux .…

DeepSeek的多模态AI模型-Janus-pro,可生图,可读图

简介 Janus-Pro 是由 DeepSeek 开发的一款多模态理解与生成模型&#xff0c;是 Janus 模型的升级版。它能够同时处理文本和图像&#xff0c;既能理解图像内容&#xff0c;又能根据文本描述生成高质量图像。Janus-Pro 的核心目标是通过解耦视觉编码路径&#xff0c;解决多模态理…

Python爬虫实战:一键采集电商数据,掌握市场动态!

电商数据分析是个香饽饽&#xff0c;可市面上的数据采集工具要不贵得吓人&#xff0c;要不就是各种广告弹窗。干脆自己动手写个爬虫&#xff0c;想抓啥抓啥&#xff0c;还能学点技术。今天咱聊聊怎么用Python写个简单的电商数据爬虫。 打好基础&#xff1a;搞定请求头 别看爬虫…

游戏引擎 Unity - Unity 下载与安装

Unity Unity 首次发布于 2005 年&#xff0c;属于 Unity Technologies Unity 使用的开发技术有&#xff1a;C# Unity 的适用平台&#xff1a;PC、主机、移动设备、VR / AR、Web 等 Unity 的适用领域&#xff1a;开发中等画质中小型项目 Unity 适合初学者或需要快速上手的开…

理解 C 与 C++ 中的 const 常量与数组大小的关系

博客主页&#xff1a; [小ᶻ☡꙳ᵃⁱᵍᶜ꙳] 本文专栏: C语言 文章目录 &#x1f4af;前言&#x1f4af;数组大小的常量要求&#x1f4af;C 语言中的数组大小要求&#x1f4af;C 中的数组大小要求&#x1f4af;为什么 C 中 const 变量可以作为数组大小&#x1f4af;进一步的…