javascript技巧

关注公众号 jb51net

关闭
首页 > 网络编程 > JavaScript > javascript技巧 > 前端字符串/数组操作

前端常用字符串/数组操作方法实例(含相关手撕)

作者:牛牛写博客

前端开发必备的10个JavaScript对象数组操作技巧,涵盖创建、遍历、筛选、转换、排序、统计、去重、合并、更新和分页等核心场景,这篇文章主要介绍了前端常用字符串/数组操作方法的相关资料,需要的朋友可以参考下

字符串转数组的方法

1.split()- 最常用的方法

功能描述:使用指定的分隔符将字符串分割成字符串数组

语法

str.split([separator[, limit]])

参数

示例

const str = "apple,banana,orange";
const arr = str.split(","); 
// 结果: ["apple", "banana", "orange"]
​
const str2 = "hello";
const arr2 = str2.split(""); 
// 结果: ["h", "e", "l", "l", "o"]
​
const str3 = "apple,banana,orange,grape";
const arr3 = str3.split(",", 2); 
// 结果: ["apple", "banana"]

2.Array.from()- 从类数组对象创建

功能描述:从类数组或可迭代对象创建一个新的数组实例

语法

Array.from(arrayLike[, mapFn[, thisArg]])

参数

示例

const str = "hello";
const arr = Array.from(str); 
// 结果: ["h", "e", "l", "l", "o"]
​
const str2 = "123";
const arr2 = Array.from(str2, Number); 
// 结果: [1, 2, 3]
​
const str3 = "hello";
const arr3 = Array.from(str3, char => char.toUpperCase()); 
// 结果: ["H", "E", "L", "L", "O"]

3. 扩展运算符...

功能描述:将字符串展开为字符数组,适用于Unicode字符

语法

[...string]

示例

const str = "hello";
const arr = [...str]; 
// 结果: ["h", "e", "l", "l", "o"]
​
const str2 = "👍😊";
const arr2 = [...str2]; 
// 结果: ["👍", "😊"]
​
const str3 = "hello world";
const arr3 = [...new Set([...str3])]; 
// 结果: ["h", "e", "l", "o", " ", "w", "r", "d"] (去重)

4.Object.assign()- 较少使用

功能描述:将字符串作为数组-like对象,将其属性分配给新数组

语法

Object.assign(target, source)

示例

const str = "hello";
const arr = Object.assign([], str); 
// 结果: ["h", "e", "l", "l", "o"]

数组转字符串的方法

1.join()- 最常用的方法

功能描述:将数组的所有元素连接成一个字符串,可指定分隔符

语法

arr.join([separator])

参数

示例

const arr = ["apple", "banana", "orange"];
const str = arr.join(", "); 
// 结果: "apple, banana, orange"
​
const arr2 = [1, 2, 3];
const str2 = arr2.join("-"); 
// 结果: "1-2-3"
​
const arr3 = ["apple", "banana", "orange"];
const str3 = arr3.join(""); 
// 结果: "applebananaorange"
​
const arr4 = ["apple", "banana", "orange"];
const str4 = arr4.join(); 
// 结果: "apple,banana,orange" (默认逗号分隔)

2.toString()- 默认逗号分隔

功能描述:返回由数组元素组成的字符串,默认用逗号分隔

语法

arr.toString()

示例

const arr = ["apple", "banana", "orange"];
const str = arr.toString(); 
// 结果: "apple,banana,orange"
​
const arr2 = [1, 2, 3];
const str2 = arr2.toString(); 
// 结果: "1,2,3"
​
const arr3 = [1, [2, 3], [4, [5, 6]]];
const str3 = arr3.toString(); 
// 结果: "1,2,3,4,5,6" (会展开嵌套数组)

3.JSON.stringify()- 转换为JSON字符串

功能描述:将数组转换为JSON字符串格式

语法

JSON.stringify(value[, replacer[, space]])

参数

示例

const arr = ["apple", "banana", "orange"];
const str = JSON.stringify(arr); 
// 结果: '["apple","banana","orange"]'
​
const arr2 = [1, 2, 3];
const str2 = JSON.stringify(arr2); 
// 结果: "[1,2,3]"
​
const arr3 = [{name: "apple"}, {name: "banana"}];
const str3 = JSON.stringify(arr3, null, 2); 
/* 结果: 
[
  {
    "name": "apple"
  },
  {
    "name": "banana"
  }
]
*/

4. 模板字符串 + 扩展运算符

功能描述:使用模板字符串和扩展运算符连接数组元素

小牛发言:有toString的效果

语法

`${[...array]}`

示例

const arr = ["apple", "banana", "orange"];
const str = `${[...arr]}`; 
// 结果: "apple,banana,orange"
​
const arr2 = [1, 2, 3];
const str2 = `${arr2}`; 
// 结果: "1,2,3"
​
const arr3 = ["apple", "banana", "orange"];
const str3 = `水果: ${arr3.join(" + ")}`; 
// 结果: "水果: apple + banana + orange"

综合应用示例

字符串反转(通过数组转换)

const original = "hello";
const reversed = [...original].reverse().join(""); 
// 结果: "olleh"
​
const sentence = "Hello World";
const reversedWords = sentence.split(" ").map(word => [...word].reverse().join("")).join(" "); 
// 结果: "olleH dlroW"

数据清洗和格式化

// 清理用户输入
const userInput = "  apple, banana , orange  ";
const cleanArray = userInput.split(",").map(item => item.trim()).filter(item => item !== "");
// 结果: ["apple", "banana", "orange"]
​
// 数字数组格式化
const numbers = [1, 2, 3, 4, 5];
const formatted = numbers.join(" - "); 
// 结果: "1 - 2 - 3 - 4 - 5"

URL参数处理

// URL参数转对象
const queryString = "name=John&age=30&city=NewYork";
const params = queryString.split("&").reduce((acc, pair) => {
  const [key, value] = pair.split("=");
  acc[key] = value;
  return acc;
}, {});
// 结果: {name: "John", age: "30", city: "NewYork"}
​
// 对象转URL参数
const paramsObj = {name: "John", age: 30, city: "New York"};
const query = Object.entries(paramsObj).map(([key, value]) => 
  `${encodeURIComponent(key)}=${encodeURIComponent(value)}`
).join("&");
// 结果: "name=John&age=30&city=New%20York"

说明(简短)

encodeURI 的区别(要点)

实例:

const params = { name: "John Doe", city: "New York/NY" };
const qs = Object.entries(params)
  .map(([k, v]) => `${encodeURIComponent(k)}=${encodeURIComponent(v)}`)
  .join('&');
// qs -> "name=John%20Doe&city=New%20York%2FNY"

注意事项

注意事项

  1. 空字符串处理

    "".split(",") // 返回 [""] 而不是 []
  2. 特殊字符转义

    // 正则特殊字符需要转义
    "a.b.c".split(".") // 正确
    "a.b.c".split(/\./) // 使用正则时需要转义
  3. 性能考虑

    • 对于大数据量,split() 通常性能最佳

    • 扩展运算符在简单场景下性能良好

  4. Unicode字符处理

    // 扩展运算符和Array.from()能正确处理Unicode
    "👍😊".split("") // 可能不正确
    [..."👍😊"] // 正确: ["👍", "😊"]
    Array.from("👍😊") // 正确: ["👍", "😊"]

数组常用方法

1. 添加/删除元素方法

push()

const arr = [1, 2, 3];
const length = arr.push(4, 5);
console.log(arr); // [1, 2, 3, 4, 5]
console.log(length); // 5

pop()

const arr = [1, 2, 3];
const last = arr.pop();
console.log(arr); // [1, 2]
console.log(last); // 3

unshift()

const arr = [2, 3];
const length = arr.unshift(0, 1);
console.log(arr); // [0, 1, 2, 3]
console.log(length); // 4

shift()

const arr = [1, 2, 3];
const first = arr.shift();
console.log(arr); // [2, 3]
console.log(first); // 1

splice()

const arr = [1, 2, 3, 4, 5];
const removed = arr.splice(2, 1, 'a', 'b');
console.log(arr); // [1, 2, 'a', 'b', 4, 5]
console.log(removed); // [3]

2. 查找和筛选方法

indexOf()

const arr = [1, 2, 3, 2, 1];
console.log(arr.indexOf(2)); // 1
console.log(arr.indexOf(4)); // -1

lastIndexOf()

const arr = [1, 2, 3, 2, 1];
console.log(arr.lastIndexOf(2)); // 3

includes()

const arr = [1, 2, 3];
console.log(arr.includes(2)); // true
console.log(arr.includes(4)); // false

find()

const arr = [5, 12, 8, 130, 44];
const found = arr.find(element => element > 10);
console.log(found); // 12

findIndex()

const arr = [5, 12, 8, 130, 44];
const index = arr.findIndex(element => element > 10);
console.log(index); // 1

filter()

const arr = [1, 2, 3, 4, 5];
const evens = arr.filter(num => num % 2 === 0);
console.log(evens); // [2, 4]

3. 遍历和转换方法

forEach()

const arr = [1, 2, 3];
arr.forEach((item, index) => {
  console.log(`索引${index}: ${item}`);
});

map()

const arr = [1, 2, 3];
const doubled = arr.map(num => num * 2);
console.log(doubled); // [2, 4, 6]

reduce()

const arr = [1, 2, 3, 4];
const sum = arr.reduce((acc, cur) => acc + cur, 0);
console.log(sum); // 10

reduceRight()

const arr = [1, 2, 3, 4];
const result = arr.reduceRight((acc, cur) => acc - cur);
console.log(result); // -2

4. 排序和重组方法

sort()

const arr = [3, 1, 4, 1, 5];
arr.sort();
console.log(arr); // [1, 1, 3, 4, 5]
​
// 数字排序
const numbers = [40, 100, 1, 5, 25];
numbers.sort((a, b) => a - b);
console.log(numbers); // [1, 5, 25, 40, 100]

reverse()

const arr = [1, 2, 3];
arr.reverse();
console.log(arr); // [3, 2, 1]

slice()

const arr = [1, 2, 3, 4, 5];
const part = arr.slice(1, 4);
console.log(part); // [2, 3, 4]

concat()

const arr1 = [1, 2];
const arr2 = [3, 4];
const merged = arr1.concat(arr2);
console.log(merged); // [1, 2, 3, 4]

5. 其他常用方法

join()

const arr = ['a', 'b', 'c'];
console.log(arr.join()); // "a,b,c"
console.log(arr.join('')); // "abc"
console.log(arr.join('-')); // "a-b-c"

toString()

const arr = [1, 2, 'a', '1a'];
console.log(arr.toString()); // "1,2,a,1a"

every()

const arr = [1, 2, 3, 4];
const allPositive = arr.every(num => num > 0);
console.log(allPositive); // true

some()

const arr = [1, 2, 3, 4];
const hasEven = arr.some(num => num % 2 === 0);
console.log(hasEven); // true

isArray()

console.log(Array.isArray([1, 2, 3])); // true
console.log(Array.isArray({})); // false

字符串常用方法

1. 查找和提取方法

indexOf()

const str = 'Hello World';
console.log(str.indexOf('o')); // 4
console.log(str.indexOf('World')); // 6

lastIndexOf()

const str = 'Hello World';
console.log(str.lastIndexOf('o')); // 7

includes()

const str = 'Hello World';
console.log(str.includes('World')); // true
console.log(str.includes('world')); // false

startsWith()

const str = 'Hello World';
console.log(str.startsWith('Hello')); // true
console.log(str.startsWith('World')); // false

endsWith()

const str = 'Hello World';
console.log(str.endsWith('World')); // true
console.log(str.endsWith('Hello')); // false

charAt()

const str = 'Hello';
console.log(str.charAt(1)); // 'e'

charCodeAt()

const str = 'Hello';
console.log(str.charCodeAt(1)); // 101

2. 修改和转换方法

toUpperCase()

const str = 'Hello';
console.log(str.toUpperCase()); // 'HELLO'

toLowerCase()

const str = 'Hello';
console.log(str.toLowerCase()); // 'hello'

trim()

const str = '  Hello World  ';
console.log(str.trim()); // 'Hello World'

trimStart() / trimLeft()

const str = '  Hello World  ';
console.log(str.trimStart()); // 'Hello World  '

trimEnd() / trimRight()

const str = '  Hello World  ';
console.log(str.trimEnd()); // '  Hello World'

replace()

const str = 'Hello World';
console.log(str.replace('World', 'JavaScript')); // 'Hello JavaScript'
​
// 使用正则表达式
console.log(str.replace(/o/g, '0')); // 'Hell0 W0rld'

replaceAll()

const str = 'Hello World';
console.log(str.replaceAll('l', 'L')); // 'HeLLo WorLd'

padStart()

const str = '5';
console.log(str.padStart(3, '0')); // '005'

padEnd()

const str = '5';
console.log(str.padEnd(3, '0')); // '500'

3. 分割和连接方法

split()

const str = 'apple,banana,orange';
console.log(str.split(',')); // ['apple', 'banana', 'orange']
​
const str2 = 'Hello';
console.log(str2.split('')); // ['H', 'e', 'l', 'l', 'o']

concat()

const str1 = 'Hello';
const str2 = 'World';
console.log(str1.concat(' ', str2)); // 'Hello World'

repeat()

const str = 'Hello';
console.log(str.repeat(3)); // 'HelloHelloHello'

4. 切片和子串方法

slice()

const str = 'Hello World';
console.log(str.slice(0, 5)); // 'Hello'
console.log(str.slice(6)); // 'World'
console.log(str.slice(-5)); // 'World'

substring()

const str = 'Hello World';
console.log(str.substring(0, 5)); // 'Hello'
console.log(str.substring(6)); // 'World'

substr()

const str = 'Hello World';
console.log(str.substr(0, 5)); // 'Hello'
console.log(str.substr(6, 5)); // 'World'

5. 其他常用方法

valueOf()

const str = new String('Hello');
console.log(str.valueOf()); // 'Hello'

toString()

const str = new String('Hello');
console.log(str.toString()); // 'Hello'

match()

const str = 'The rain in SPAIN stays mainly in the plain';
console.log(str.match(/ain/g)); // ['ain', 'ain', 'ain']

search()

const str = 'The rain in SPAIN stays mainly in the plain';
console.log(str.search(/ain/)); // 5

localeCompare()

console.log('a'.localeCompare('b')); // -1
console.log('b'.localeCompare('a')); // 1
console.log('a'.localeCompare('a')); // 0

总结

数组方法特点

字符串方法特点

常用场景

  1. 数据处理: map, filter, reduce

  2. 元素操作: push, pop, splice

  3. 字符串处理: split, join, replace

  4. 查找判断: includes, indexOf, find

  5. 格式转换: toString, toUpperCase, toLowerCase

到此这篇关于前端常用字符串/数组操作方法的文章就介绍到这了,更多相关前端字符串/数组操作内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文