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

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

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.kler.cn/a/534253.html

相关文章:

  • 大型三甲医院算力网络架构的深度剖析与关键技术探索
  • 四.4 Redis 五大数据类型/结构的详细说明/详细使用( zset 有序集合数据类型详解和使用)
  • “AI智能分析综合管理系统:企业管理的智慧中枢
  • 修剪二叉搜索树(力扣669)
  • 0205算法:最长连续序列、三数之和、排序链表
  • 【Leetcode】4. 寻找两个正序数组的中位数
  • 30.日常算法
  • 【Elasticsearch】 日期直方图聚合(`date_histogram`)
  • IC卡读卡器web插件YOWOCloudRFIDReader.js
  • 基于ArcGIS的SWAT模型+CENTURY模型模拟流域生态系统水-碳-氮耦合过程研究
  • C# Monitor类 使用详解
  • K8S学习笔记-------2.极简易懂的入门示例
  • OSCP - Other Machines - sar2HTML
  • JeecgBoot 对接本地化的大模型 DeepSeek-R1
  • 64.进度条 C#例子 WPF例子
  • vue3中的ref相关的api及用法
  • 离散时间傅里叶变换(DTFT)公式详解:周期性与连续性剖析
  • matlab实现了一个多视角受限核机算法,结合了多个视角的数据进行二分类任务
  • 2.5学习总结
  • Unity渲染管线
  • Windows下从零开始基于Ollama与Open-WebUI本地部署deepseek R1详细指南(包含软件包和模型网盘下载)
  • Linux系统 环境变量
  • ​K8S运行时切换-从Docker到Containerd的切换实战
  • 软件测试丨PyTorch 简介
  • 后端【代码审查】C语言。
  • 使用 Axios 获取用户数据并渲染——个人信息设置+头像修改