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

news/2025/2/6 15:33:56 标签: es6, 前端, ecmascript

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.niftyadmin.cn/n/5843138.html

相关文章

基础相对薄弱怎么考研

复习总体规划 明确目标 选择专业和院校&#xff1a;根据你的兴趣、职业规划和自身实力&#xff0c;选择适合自己的专业和院校。可以参考往年的分数线、报录比、复试难度等。了解考试科目&#xff1a;不同专业考试科目不同&#xff0c;一般包括&#xff1a; 公共课&#xff1a…

java 日常下拉框接口字典封装

Operation(description "字典") GetMapping("/dict") public Result dict() {Long userItemId super.getUserItemId();Page<Manure> objectPage new Page<>();objectPage.setSize(100000);objectPage.setCurrent(1);Page<Manure> pag…

MacBook Pro(M1芯片)DeepSeek R1 本地大模型环境搭建

MacBook Pro&#xff08;M1芯片&#xff09;DeepSeek R1 本地大模型环境搭建 这一阵子deepseek真的是太火了&#xff0c;这不&#xff0c;R1出来后更是掀起AI的狂欢&#xff0c;作为一个AI的外行人&#xff0c;也是忍不住想要拿过来感受一番&#xff5e;&#xff5e; 主要呢&…

Java进阶14 TCP日志枚举

Java进阶14 TCP&日志&枚举 一、网络编程TCP Java对基于TCP协议得网络提供了良好的封装&#xff0c;使用Socket对象来代表两端的通信端口&#xff0c;并通过Socket产生IO流来进行网络通信。 1、TCP协议发数据 1.1 构造方法 方法 说明 Socket(InetAddress address…

微前端如何实现作用域隔离

微前端是一种架构风格,它将前端应用拆分为多个独立的子应用,使得各个子应用可以独立开发、部署和维护。在微前端架构中,作用域隔离是一个关键问题,确保不同子应用之间的样式、脚本和状态不会冲突。本文将讨论几种实现作用域隔离的方法。 1. CSS 作用域隔离 1.1 CSS Modul…

多用户同时RDP登入Win10

自备以下文件&#xff1a; winsw_frpc.xml展开如下&#xff1a; <service><!-- ID of the service. It should be unique across the Windows system--><id>winsw_frp</id><!-- Display name of the service --><name>winsw_frp</na…

uniapp小程序自定义中间凸起样式底部tabbar

我自己写的自定义的tabbar效果图 废话少说咱们直接上代码&#xff0c;一步一步来 第一步&#xff1a; 找到根目录下的 pages.json 文件&#xff0c;在 tabBar 中把 custom 设置为 true&#xff0c;默认值是 false。list 中设置自定义的相关信息&#xff0c; pagePath&#x…

Windows下从零开始基于Ollama与Open-WebUI本地部署deepseek R1详细指南(包含软件包和模型网盘下载)

0. 概述 最近国产大模型DeepSeek很火&#xff0c;但有时因为访问人数过多导致反应慢甚至宕机。 但好在DeepSeek是开源的&#xff0c;可以本地部署&#xff0c;这样就不用联网也能用了。但本地部署需要考虑硬件需求&#xff0c;比如是否有足够的GPU资源&#xff0c;存储空间&a…