JavaScript手录09-内置对象【String对象】

在 JavaScript 中,内置对象(Built-in Objects)是指由 ECMAScript 标准定义、浏览器或 JavaScript 引擎自带的对象,无需额外引入即可直接使用。这些对象提供了丰富的功能,涵盖数据处理、DOM 操作、日期处理等多个领域。

JavaScript中一共有26个内置对象,本章主要介绍 - String对象

在开始之前需要了解的概念

面向对象编程(OOP)

定义:一种以 "对象" 为中心的编程思想,将数据(属性)和操作数据的方法封装在对象中,注重 "做什么"(目标)而非 "怎么做"(步骤)。

核心特性:
  • 封装:将属性和方法封装在对象中,隐藏内部细节。
  • 继承:子类可复用父类的属性和方法(减少重复代码)。
  • 多态:不同对象对同一方法可有不同实现(增强灵活性)。
示例(用对象封装圆的功能):
javascript 复制代码
// 面向对象:用类封装属性和方法
class Circle {
  // 构造函数:初始化属性
  constructor(radius) {
    this.radius = radius; // 数据(属性)
  }

  // 方法:操作数据
  calculateArea() {
    return Math.PI * this.radius **2;
  }

  calculateCircumference() {
    return 2 * Math.PI * this.radius;
  }
}

// 使用:创建对象(实例)
const circle = new Circle(5);
console.log("面积:", circle.calculateArea());
console.log("周长:", circle.calculateCircumference());

面向过程编程(POP)

定义:一种以 "过程" 为中心的编程思想,通过一步步编写函数(过程)实现功能,注重 "怎么做"(步骤)。

特点:
  • 代码按步骤拆分,用函数实现独立功能。
  • 数据与函数分离,函数通过参数接收数据并处理。
  • 适合简单逻辑,代码直观但可复用性差。
示例(计算圆的面积和周长):
javascript 复制代码
// 面向过程:按步骤编写函数
function calculateArea(radius) {
  return Math.PI * radius * radius;
}

function calculateCircumference(radius) {
  return 2 * Math.PI * radius;
}

// 使用
const r = 5;
console.log("面积:", calculateArea(r));
console.log("周长:", calculateCircumference(r));

JavaScript中的基本包装类型(Primitive Wrapper Types)

JavaScript 中,基本数据类型(<font style="color:rgba(0, 0, 0, 0.85) !important;">string</font><font style="color:rgba(0, 0, 0, 0.85) !important;">number</font><font style="color:rgba(0, 0, 0, 0.85) !important;">boolean</font>)本身不是对象,但为了让它们能使用对象的方法(如 <font style="color:rgba(0, 0, 0, 0.85) !important;">str.trim()</font>),JS 引擎在后台创建了临时对象,这些对象称为 "基本包装类型"。

原理:

当基本类型调用方法时,JS 会自动完成以下步骤:

  1. 创建对应的包装对象(如 <font style="color:rgb(0, 0, 0);">new String(str)</font>)。
  2. 调用包装对象的方法。
  3. 立即销毁包装对象。
javascript 复制代码
const str = "hello";
str.toUpperCase(); // "HELLO"

// 等价于:
const temp = new String("hello"); // 临时包装对象
temp.toUpperCase(); // "HELLO"
temp = null; // 销毁临时对象
三种基本包装类型:
  1. String 对应 <font style="color:rgb(0, 0, 0);">string</font> 类型,如 <font style="color:rgb(0, 0, 0);">new String("abc")</font>
  2. Number 对应 <font style="color:rgb(0, 0, 0);">number</font> 类型,如 <font style="color:rgb(0, 0, 0);">new Number(123)</font>
  3. Boolean : 对应 <font style="color:rgba(0, 0, 0, 0.85) !important;">boolean</font> 类型,如 <font style="color:rgba(0, 0, 0, 0.85) !important;">new Boolean(true)</font>
注意事项:
  • 基本类型与包装对象的区别:
javascript 复制代码
const str1 = "hello"; // 基本类型(string)
const str2 = new String("hello"); // 包装对象(object)
console.log(str1 === str2); // false(类型不同)
  • 避免手动创建包装对象:这可能会导致类型判断错误(如 <font style="color:rgba(0, 0, 0, 0.85) !important;">typeof new String("a")</font><font style="color:rgba(0, 0, 0, 0.85) !important;">object</font>,而非 <font style="color:rgba(0, 0, 0, 0.85) !important;">string</font>)。

内置对象 - String

<font style="color:rgba(0, 0, 0, 0.85);">String</font> 是 JavaScript 中处理文本数据的内置对象,用于创建和操作字符串。

它既是基本数据类型(<font style="color:rgba(0, 0, 0, 0.85);">string</font>)的包装对象,也提供了丰富的方法处理字符串。

String 对象的创建

  • 字面量形式(推荐):直接使用单引号、双引号或反引号定义,实际是基本数据类型。
javascript 复制代码
const str1 = "hello"; // 基本类型 string
const str2 = `world`; // 模板字符串(支持换行和变量插入)
  • 构造函数形式 :通过 <font style="color:rgba(0, 0, 0, 0.85);">new String()</font> 创建,返回对象类型。
javascript 复制代码
const strObj = new String("hello"); // 引用类型 object
console.log(typeof strObj); // "object"

String 对象的常用属性

  • 属性<font style="color:rgb(0, 0, 0);">length</font>
  • **功能:**返回字符串的长度(字符数量)。
  • 示例
javascript 复制代码
const str = "hello";
console.log(str.length); // 5
const emptyStr = "";
console.log(emptyStr.length); // 0

String对象的常用方法

查找与判断方法
  1. indexOf(searchValue, fromIndex)]
  • 功能 :从 <font style="color:rgb(0, 0, 0);">fromIndex</font>(默认 0)开始,查找 <font style="color:rgb(0, 0, 0);">searchValue</font> 首次出现的索引,未找到返回 <font style="color:rgb(0, 0, 0);">-1</font>
  • 示例
javascript 复制代码
const str = "hello world";
console.log(str.indexOf("o")); // 4(首次出现的索引)
console.log(str.indexOf("o", 5)); // 7(从索引5开始查找)
console.log(str.indexOf("xyz")); // -1(未找到)
  1. lastIndexOf(searchValue, fromIndex)
  • 功能 :从 <font style="color:rgb(0, 0, 0);">fromIndex</font>(默认字符串末尾)开始,反向查找 <font style="color:rgb(0, 0, 0);">searchValue</font> 最后一次出现的索引。
  • 示例
javascript 复制代码
const str = "hello world";
console.log(str.lastIndexOf("o")); // 7(最后一次出现的索引)
  1. includes(searchValue, fromIndex)
  • 功能 :判断字符串是否包含 <font style="color:rgb(0, 0, 0);">searchValue</font>,返回布尔值。
  • 示例
javascript 复制代码
const str = "hello";
console.log(str.includes("ll")); // true
console.log(str.includes("xyz")); // false
console.log(str.includes("e", 2)); // false(从索引2开始不包含"e")
  1. startsWith(searchValue, fromIndex)
  • 功能 :判断字符串是否以 <font style="color:rgb(0, 0, 0);">searchValue</font> 开头(从 <font style="color:rgb(0, 0, 0);">fromIndex</font> 位置开始算)。
  • 示例
javascript 复制代码
const str = "hello world";
console.log(str.startsWith("hello")); // true
console.log(str.startsWith("world", 6)); // true(从索引6开始以"world"开头)
  1. endsWith(searchValue, fromIndex)
  • 功能 :判断字符串是否以 <font style="color:rgb(0, 0, 0);">searchValue</font> 结尾(<font style="color:rgb(0, 0, 0);">length</font> 可选,指定字符串的前 <font style="color:rgb(0, 0, 0);">length</font> 个字符)。
  • 示例
javascript 复制代码
const str = "hello world";
console.log(str.endsWith("world")); // true
console.log(str.endsWith("hello", 5)); // true(前5个字符是"hello")
转换与格式化方法
  1. toUpperCase()
  • 功能:将字符串转换为大写。
  • 示例
javascript 复制代码
const str = "Hello World";
console.log(str.toUpperCase()); // "HELLO WORLD"
  1. toLowerCase()
  • 功能:将字符串转换为小写。
  • 示例
javascript 复制代码
console.log(str.toLowerCase()); // "hello world"
  1. trim()
  • 功能 :去除字符串首尾的空格(包括换行符 <font style="color:rgb(0, 0, 0);">\n</font>、制表符 <font style="color:rgb(0, 0, 0);">\t</font> 等空白字符)。
  • 示例
javascript 复制代码
const str = "  hello  \n";
console.log(str.trim()); // "hello"(首尾空白被移除)
  1. trimStart() / trimLeft()
  • 功能:仅去除字符串开头的空白。
  • 示例
javascript 复制代码
console.log(str.trimStart()); // "hello  \n"(仅开头空白被移除)
  1. trimEnd() / trimRight()
  • 功能:仅去除字符串结尾的空白。
  • 示例
javascript 复制代码
console.log(str.trimEnd()); // "  hello"(仅结尾空白被移除)
截取与分割方法
  1. slice(startIndex, endIndex)
  • 功能 :截取从 <font style="color:rgb(0, 0, 0);">startIndex</font><font style="color:rgb(0, 0, 0);">endIndex</font>(不包含 <font style="color:rgb(0, 0, 0);">endIndex</font>)的子串,支持负数索引(从末尾计算)。
  • 示例
javascript 复制代码
const str = "abcdef";
console.log(str.slice(1, 4)); // "bcd"(索引1到3)
console.log(str.slice(2)); // "cdef"(从索引2到末尾)
console.log(str.slice(-3)); // "def"(从倒数第3个到末尾)
  1. substring(startIndex, endIndex)
  • 功能 :类似 <font style="color:rgb(0, 0, 0);">slice</font>,但不支持负数索引,且 <font style="color:rgb(0, 0, 0);">startIndex</font> 大于 <font style="color:rgb(0, 0, 0);">endIndex</font> 时会自动交换。
  • 示例
javascript 复制代码
console.log(str.substring(4, 1)); // "bcd"(自动交换为1到4)
  1. substr(startIndex, endIndex)
  • 功能 :从 <font style="color:rgb(0, 0, 0);">startIndex</font> 开始,截取长度为 <font style="color:rgb(0, 0, 0);">length</font> 的子串(注意:部分浏览器可能不推荐使用,建议用 <font style="color:rgb(0, 0, 0);">slice</font> 替代)。
  • 示例
javascript 复制代码
console.log(str.substr(2, 3)); // "cde"(从索引2开始,截取3个字符)
  1. split(separator, limit)
  • 功能 :按 <font style="color:rgb(0, 0, 0);">separator</font> 分割字符串为数组,<font style="color:rgb(0, 0, 0);">limit</font> 限制返回的数组长度。
  • 示例
javascript 复制代码
const str = "apple,banana,orange";
console.log(str.split(",")); // ["apple", "banana", "orange"]
console.log(str.split(",", 2)); // ["apple", "banana"](只取前2个)
console.log(str.split("")); // ["a","p","p","l","e",",",...](分割为单个字符)
替换方法
  1. replace(pattern, replacement)
  • 功能 :替换第一个匹配 <font style="color:rgb(0, 0, 0);">pattern</font>(字符串或正则表达式)的子串为 <font style="color:rgb(0, 0, 0);">replacement</font>
  • 示例
javascript 复制代码
const str = "hello world";
console.log(str.replace("world", "there")); // "hello there"(替换第一个匹配)
console.log(str.replace(/o/g, "*")); // "hell* w*rld"(正则全局替换所有"o")
  1. replaceAll(pattern, replacement)
  • 功能 :替换所有匹配 <font style="color:rgb(0, 0, 0);">pattern</font> 的子串(<font style="color:rgb(0, 0, 0);">replace</font> 需配合正则 <font style="color:rgb(0, 0, 0);">g</font> 修饰符才能全局替换)。
  • 示例
javascript 复制代码
console.log(str.replaceAll("l", "x")); // "hexxo worxd"(替换所有"l")
其他实用方法
  1. charAt(Index)
  • 功能 :返回索引 <font style="color:rgb(0, 0, 0);">index</font> 处的字符(类似 <font style="color:rgb(0, 0, 0);">str[index]</font>,但 <font style="color:rgb(0, 0, 0);">str[index]</font> 在部分旧环境可能不支持)。
  • 示例
javascript 复制代码
const str = "hello";
console.log(str.charAt(1)); // "e"
  1. charCodeAt()
  • 功能 :返回索引 <font style="color:rgb(0, 0, 0);">index</font> 处字符的 Unicode 编码。
  • 示例
javascript 复制代码
console.log(str.charCodeAt(0)); // 104("h"的Unicode编码)
  1. concat(str1, str2)
  • 功能 :拼接多个字符串,返回新字符串(通常推荐用 <font style="color:rgb(0, 0, 0);">+</font> 或模板字符串替代,更简洁)。
  • 示例
javascript 复制代码
const str1 = "hello";
const str2 = "world";
console.log(str1.concat(" ", str2)); // "hello world"
  1. padStart(targetLength, padString)
  • 功能 :在字符串开头填充 <font style="color:rgb(0, 0, 0);">padString</font>,直到总长度为 <font style="color:rgb(0, 0, 0);">targetLength</font>
  • 示例
javascript 复制代码
const num = "123";
console.log(num.padStart(5, "0")); // "00123"(总长度5,不足补"0")
  1. padEnd(targetLength, padString)
  • 功能 :在字符串结尾填充 <font style="color:rgb(0, 0, 0);">padString</font>,直到总长度为 <font style="color:rgb(0, 0, 0);">targetLength</font>
  • 示例
javascript 复制代码
console.log(num.padEnd(5, "x")); // "123xx"
  1. repeat(count)
  • 功能 :将字符串重复 <font style="color:rgb(0, 0, 0);">count</font> 次,返回新字符串。
  • 示例
javascript 复制代码
console.log("ab".repeat(3)); // "ababab"

字符串的不可变性

字符串是不可变的:一旦创建,其字符无法被直接修改,任何修改操作都会返回新字符串。

javascript 复制代码
let str = "hello";
str[0] = "H"; // 无效操作
console.log(str); // 仍为 "hello"

// 正确修改方式:创建新字符串
str = "H" + str.slice(1); // "Hello"
相关推荐
钟离墨笺12 分钟前
Go 语言-->指针
开发语言·后端·golang
拳打南山敬老院18 分钟前
从零构建一个插件系统(四)插件的缓存
javascript·架构
new_abc25 分钟前
net-snmp添加自定义mib树
服务器·前端·javascript
超浪的晨43 分钟前
Java 代理机制详解:从静态代理到动态代理,彻底掌握代理模式的原理与实战
java·开发语言·后端·学习·代理模式·个人开发
咖啡の猫1 小时前
bash的特性-bash中的引号
开发语言·chrome·bash
樱花开了几轉1 小时前
React中的合成事件解释和理解
前端·javascript·react.js
code_life1 小时前
动态格式化时间
javascript
java叶新东老师1 小时前
idea提交时忽略.class、.iml文件和文件夹或目录的方法
java·开发语言
走过,莫回头1 小时前
在OpenMP中,#pragma omp的使用
开发语言·openmp
小高0071 小时前
告别“if-else”条件判断:5 个让 JavaScript 逻辑更优雅的写法
前端·javascript