最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

前端常用字符串/數(shù)組操作方法實例(含相關(guān)手撕)

 更新時間:2026年03月17日 10:10:38   作者:牛牛寫博客  
前端開發(fā)必備的10個JavaScript對象數(shù)組操作技巧,涵蓋創(chuàng)建、遍歷、篩選、轉(zhuǎn)換、排序、統(tǒng)計、去重、合并、更新和分頁等核心場景,這篇文章主要介紹了前端常用字符串/數(shù)組操作方法的相關(guān)資料,需要的朋友可以參考下

字符串轉(zhuǎn)數(shù)組的方法

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

功能描述:使用指定的分隔符將字符串分割成字符串數(shù)組

語法

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

參數(shù)

  • separator:指定表示每個拆分點的字符串,如果省略,則返回包含整個字符串的數(shù)組

  • limit:可選,限制返回的數(shù)組片段數(shù)量

示例

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

2.Array.from()- 從類數(shù)組對象創(chuàng)建

功能描述:從類數(shù)組或可迭代對象創(chuàng)建一個新的數(shù)組實例

語法

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

參數(shù)

  • arrayLike:要轉(zhuǎn)換為數(shù)組的類數(shù)組或可迭代對象

  • mapFn:可選,映射函數(shù),用于對每個元素進行處理

  • thisArg:可選,執(zhí)行映射函數(shù)時的this值

示例

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

3. 擴展運算符...

功能描述:將字符串展開為字符數(shù)組,適用于Unicode字符

語法

[...string]

示例

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

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

功能描述:將字符串作為數(shù)組-like對象,將其屬性分配給新數(shù)組

語法

Object.assign(target, source)

示例

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

數(shù)組轉(zhuǎn)字符串的方法

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

功能描述:將數(shù)組的所有元素連接成一個字符串,可指定分隔符

語法

arr.join([separator])

參數(shù)

  • separator:可選,指定分隔符,默認為逗號

示例

const arr = ["apple", "banana", "orange"];
const str = arr.join(", "); 
// 結(jié)果: "apple, banana, orange"
?
const arr2 = [1, 2, 3];
const str2 = arr2.join("-"); 
// 結(jié)果: "1-2-3"
?
const arr3 = ["apple", "banana", "orange"];
const str3 = arr3.join(""); 
// 結(jié)果: "applebananaorange"
?
const arr4 = ["apple", "banana", "orange"];
const str4 = arr4.join(); 
// 結(jié)果: "apple,banana,orange" (默認逗號分隔)

2.toString()- 默認逗號分隔

功能描述:返回由數(shù)組元素組成的字符串,默認用逗號分隔

語法

arr.toString()

示例

const arr = ["apple", "banana", "orange"];
const str = arr.toString(); 
// 結(jié)果: "apple,banana,orange"
?
const arr2 = [1, 2, 3];
const str2 = arr2.toString(); 
// 結(jié)果: "1,2,3"
?
const arr3 = [1, [2, 3], [4, [5, 6]]];
const str3 = arr3.toString(); 
// 結(jié)果: "1,2,3,4,5,6" (會展開嵌套數(shù)組)

3.JSON.stringify()- 轉(zhuǎn)換為JSON字符串

功能描述:將數(shù)組轉(zhuǎn)換為JSON字符串格式

語法

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

參數(shù)

  • value:要轉(zhuǎn)換為JSON字符串的值

  • replacer:可選,轉(zhuǎn)換結(jié)果的函數(shù)或數(shù)組

  • space:可選,用于縮進的空格數(shù)或字符串

示例

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

4. 模板字符串 + 擴展運算符

功能描述:使用模板字符串和擴展運算符連接數(shù)組元素

小牛發(fā)言:有toString的效果

語法

`${[...array]}`

示例

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

綜合應(yīng)用示例

字符串反轉(zhuǎn)(通過數(shù)組轉(zhuǎn)換)

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

數(shù)據(jù)清洗和格式化

// 清理用戶輸入
const userInput = "  apple, banana , orange  ";
const cleanArray = userInput.split(",").map(item => item.trim()).filter(item => item !== "");
// 結(jié)果: ["apple", "banana", "orange"]
?
// 數(shù)字數(shù)組格式化
const numbers = [1, 2, 3, 4, 5];
const formatted = numbers.join(" - "); 
// 結(jié)果: "1 - 2 - 3 - 4 - 5"

URL參數(shù)處理

// URL參數(shù)轉(zhuǎn)對象
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;
}, {});
// 結(jié)果: {name: "John", age: "30", city: "NewYork"}
?
// 對象轉(zhuǎn)URL參數(shù)
const paramsObj = {name: "John", age: 30, city: "New York"};
const query = Object.entries(paramsObj).map(([key, value]) => 
  `${encodeURIComponent(key)}=${encodeURIComponent(value)}`
).join("&");
// 結(jié)果: "name=John&age=30&city=New%20York"

說明(簡短)

  • encodeURIComponent 是瀏覽器和 Node.js 中的全局函數(shù),用于對 URI 的單個組件進行編碼:先把字符串按 UTF-8 編碼,再把非安全字符用百分號轉(zhuǎn)義(%xx)。

  • 它會對大多數(shù)保留字符進行編碼(例如 :/?&=+#, 等),保留字符中只有 A–Z a–z 0–9 和 - _ . ! ~ * ' ( ) 不會被編碼。

  • 常用于對 URL 的查詢參數(shù)名和值進行編碼,避免因特殊字符導(dǎo)致的解析錯誤。對應(yīng)的解碼函數(shù)是 decodeURIComponent

encodeURI 的區(qū)別(要點)

  • encodeURI 用于編碼整個 URI,不會編碼 URI 中有意義的分隔符(如 :, /, ?, #),因此不會把這些分隔符轉(zhuǎn)義。

  • encodeURIComponent 更“嚴格”,適合編碼單個參數(shù)或路徑段,因為它會把更多字符轉(zhuǎn)義,避免破壞結(jié)構(gòu)性分隔符。

實例:

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"

注意事項

  • 空格被編碼為 %20(不是 +)。如果要生成 application/x-www-form-urlencoded 風(fēng)格,可在需要時把 %20 替換為 +。

  • 使用 decodeURIComponent 恢復(fù)原始字符串。

  • 在現(xiàn)代瀏覽器和 Node.js 都可用,是 ECMAScript 標準的一部分。

注意事項

  1. 空字符串處理

    "".split(",") // 返回 [""] 而不是 []
  2. 特殊字符轉(zhuǎn)義

    // 正則特殊字符需要轉(zhuǎn)義
    "a.b.c".split(".") // 正確
    "a.b.c".split(/\./) // 使用正則時需要轉(zhuǎn)義
  3. 性能考慮

    • 對于大數(shù)據(jù)量,split() 通常性能最佳

    • 擴展運算符在簡單場景下性能良好

  4. Unicode字符處理

    // 擴展運算符和Array.from()能正確處理Unicode
    "????".split("") // 可能不正確
    [..."????"] // 正確: ["??", "??"]
    Array.from("????") // 正確: ["??", "??"]

數(shù)組常用方法

1. 添加/刪除元素方法

push()

  • 描述: 向數(shù)組末尾添加一個或多個元素

  • 語法: arr.push(element1, ..., elementN)

  • 返回值: 數(shù)組的新長度

  • 示例:

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

pop()

  • 描述: 刪除并返回數(shù)組的最后一個元素

  • 語法: arr.pop()

  • 返回值: 被刪除的元素

  • 示例:

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

unshift()

  • 描述: 向數(shù)組開頭添加一個或多個元素

  • 語法: arr.unshift(element1, ..., elementN)

  • 返回值: 數(shù)組的新長度

  • 示例:

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

shift()

  • 描述: 刪除并返回數(shù)組的第一個元素

  • 語法: arr.shift()

  • 返回值: 被刪除的元素

  • 示例:

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

splice()

  • 描述: 在指定位置添加/刪除元素

  • 語法: arr.splice(start, deleteCount, item1, ..., itemN)

  • 返回值: 包含被刪除元素的數(shù)組

  • 示例:

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()

  • 描述: 返回指定元素在數(shù)組中第一次出現(xiàn)的索引

  • 語法: arr.indexOf(searchElement[, fromIndex])

  • 返回值: 索引值,未找到返回-1

  • 示例:

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

lastIndexOf()

  • 描述: 返回指定元素在數(shù)組中最后一次出現(xiàn)的索引

  • 語法: arr.lastIndexOf(searchElement[, fromIndex])

  • 返回值: 索引值,未找到返回-1

  • 示例:

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

includes()

  • 描述: 判斷數(shù)組是否包含某個元素

  • 語法: arr.includes(valueToFind[, fromIndex])

  • 返回值: 布爾值

  • 示例:

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

find()

  • 描述: 返回滿足條件的第一個元素

  • 語法: arr.find(callback(element[, index[, array]])[, thisArg])

  • 返回值: 找到的元素,未找到返回undefined

  • 示例:

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

findIndex()

  • 描述: 返回滿足條件的第一個元素的索引

  • 語法: arr.findIndex(callback(element[, index[, array]])[, thisArg])

  • 返回值: 索引值,未找到返回-1

  • 示例:

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

filter()

  • 描述: 返回滿足條件的所有元素組成的新數(shù)組

  • 語法: arr.filter(callback(element[, index[, array]])[, thisArg])

  • 返回值: 新數(shù)組

  • 示例:

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

3. 遍歷和轉(zhuǎn)換方法

forEach()

  • 描述: 對每個元素執(zhí)行函數(shù)

  • 語法: arr.forEach(callback(currentValue[, index[, array]])[, thisArg])

  • 返回值: undefined

  • 示例:

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

map()

  • 描述: 對每個元素執(zhí)行函數(shù)并返回新數(shù)組

  • 語法: arr.map(callback(currentValue[, index[, array]])[, thisArg])

  • 返回值: 新數(shù)組

  • 示例:

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

reduce()

  • 描述: 將數(shù)組縮減為單個值

  • 語法: arr.reduce(callback(accumulator, currentValue[, index[, array]])[, initialValue])

  • 返回值: 累積結(jié)果

  • 示例:

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

reduceRight()

  • 描述: 從右向左將數(shù)組縮減為單個值

  • 語法: arr.reduceRight(callback(accumulator, currentValue[, index[, array]])[, initialValue])

  • 返回值: 累積結(jié)果

  • 示例:

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

4. 排序和重組方法

sort()

  • 描述: 對數(shù)組排序

  • 語法: arr.sort([compareFunction])

  • 返回值: 排序后的數(shù)組

  • 示例:

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

reverse()

  • 描述: 反轉(zhuǎn)數(shù)組順序

  • 語法: arr.reverse()

  • 返回值: 反轉(zhuǎn)后的數(shù)組

  • 示例:

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

slice()

  • 描述: 提取數(shù)組的一部分

  • 語法: arr.slice([start[, end]])

  • 返回值: 新數(shù)組

  • 示例:

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

concat()

  • 描述: 合并兩個或多個數(shù)組

  • 語法: arr.concat(value1[, value2[, ...[, valueN]]])

  • 返回值: 新數(shù)組

  • 示例:

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

5. 其他常用方法

join()

  • 描述: 將數(shù)組所有元素連接成字符串

  • 語法: arr.join([separator])

  • 返回值: 字符串

  • 示例:

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()

  • 描述: 返回數(shù)組的字符串表示

  • 語法: arr.toString()

  • 返回值: 字符串

  • 示例:

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

every()

  • 描述: 檢測是否所有元素都滿足條件

  • 語法: arr.every(callback(element[, index[, array]])[, thisArg])

  • 返回值: 布爾值

  • 示例:

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

some()

  • 描述: 檢測是否有元素滿足條件

  • 語法: arr.some(callback(element[, index[, array]])[, thisArg])

  • 返回值: 布爾值

  • 示例:

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

isArray()

  • 描述: 判斷是否為數(shù)組

  • 語法: Array.isArray(value)

  • 返回值: 布爾值

  • 示例:

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

字符串常用方法

1. 查找和提取方法

indexOf()

  • 描述: 返回指定值在字符串中第一次出現(xiàn)的索引

  • 語法: str.indexOf(searchValue[, fromIndex])

  • 返回值: 索引值,未找到返回-1

  • 示例:

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

lastIndexOf()

  • 描述: 返回指定值在字符串中最后一次出現(xiàn)的索引

  • 語法: str.lastIndexOf(searchValue[, fromIndex])

  • 返回值: 索引值,未找到返回-1

  • 示例:

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

includes()

  • 描述: 判斷字符串是否包含指定子串

  • 語法: str.includes(searchString[, position])

  • 返回值: 布爾值

  • 示例:

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

startsWith()

  • 描述: 判斷字符串是否以指定子串開頭

  • 語法: str.startsWith(searchString[, position])

  • 返回值: 布爾值

  • 示例:

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

endsWith()

  • 描述: 判斷字符串是否以指定子串結(jié)尾

  • 語法: str.endsWith(searchString[, length])

  • 返回值: 布爾值

  • 示例:

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

charAt()

  • 描述: 返回指定位置的字符

  • 語法: str.charAt(index)

  • 返回值: 字符

  • 示例:

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

charCodeAt()

  • 描述: 返回指定位置字符的Unicode編碼

  • 語法: str.charCodeAt(index)

  • 返回值: Unicode編碼

  • 示例:

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

2. 修改和轉(zhuǎn)換方法

toUpperCase()

  • 描述: 將字符串轉(zhuǎn)換為大寫

  • 語法: str.toUpperCase()

  • 返回值: 新字符串

  • 示例:

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

toLowerCase()

  • 描述: 將字符串轉(zhuǎn)換為小寫

  • 語法: str.toLowerCase()

  • 返回值: 新字符串

  • 示例:

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

trim()

  • 描述: 移除字符串兩端的空白字符

  • 語法: str.trim()

  • 返回值: 新字符串

  • 示例:

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

trimStart() / trimLeft()

  • 描述: 移除字符串開頭的空白字符

  • 語法: str.trimStart()str.trimLeft()

  • 返回值: 新字符串

  • 示例:

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

trimEnd() / trimRight()

  • 描述: 移除字符串末尾的空白字符

  • 語法: str.trimEnd()str.trimRight()

  • 返回值: 新字符串

  • 示例:

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

replace()

  • 描述: 替換字符串中的子串

  • 語法: str.replace(searchValue, replaceValue)

  • 返回值: 新字符串

  • 示例:

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

replaceAll()

  • 描述: 替換字符串中所有匹配的子串

  • 語法: str.replaceAll(searchValue, replaceValue)

  • 返回值: 新字符串

  • 示例:

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

padStart()

  • 描述: 在字符串開頭填充字符直到達到指定長度

  • 語法: str.padStart(targetLength[, padString])

  • 返回值: 新字符串

  • 示例:

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

padEnd()

  • 描述: 在字符串末尾填充字符直到達到指定長度

  • 語法: str.padEnd(targetLength[, padString])

  • 返回值: 新字符串

  • 示例:

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

3. 分割和連接方法

split()

  • 描述: 將字符串分割為數(shù)組

  • 語法: str.split([separator[, limit]])

  • 返回值: 數(shù)組

  • 示例:

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()

  • 描述: 連接兩個或多個字符串

  • 語法: str.concat(str2, ..., strN)

  • 返回值: 新字符串

  • 示例:

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

repeat()

  • 描述: 將字符串重復(fù)指定次數(shù)

  • 語法: str.repeat(count)

  • 返回值: 新字符串

  • 示例:

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

4. 切片和子串方法

slice()

  • 描述: 提取字符串的一部分

  • 語法: str.slice(beginIndex[, endIndex])

  • 返回值: 新字符串

  • 示例:

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

substring()

  • 描述: 提取兩個指定索引之間的字符

  • 語法: str.substring(indexStart[, indexEnd])

  • 返回值: 新字符串

  • 示例:

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

substr()

  • 描述: 從指定位置提取指定長度的字符

  • 語法: str.substr(start[, length])

  • 返回值: 新字符串

  • 示例:

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

5. 其他常用方法

valueOf()

  • 描述: 返回字符串對象的原始值

  • 語法: str.valueOf()

  • 返回值: 字符串

  • 示例:

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

toString()

  • 描述: 返回字符串表示

  • 語法: str.toString()

  • 返回值: 字符串

  • 示例:

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

match()

  • 描述: 在字符串中查找匹配正則表達式的字符

  • 語法: str.match(regexp)

  • 返回值: 匹配結(jié)果數(shù)組或null

  • 示例:

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

search()

  • 描述: 搜索匹配正則表達式的字符的位置

  • 語法: str.search(regexp)

  • 返回值: 索引值,未找到返回-1

  • 示例:

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

localeCompare()

  • 描述: 比較兩個字符串在本地語言環(huán)境中的順序

  • 語法: str.localeCompare(compareString[, locales[, options]])

  • 返回值: 數(shù)字(負數(shù)、零或正數(shù))

  • 示例:

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

總結(jié)

數(shù)組方法特點

  • 改變原數(shù)組: push, pop, unshift, shift, splice, sort, reverse

  • 不改變原數(shù)組: slice, concat, map, filter, reduce, join, toString

  • 返回新數(shù)組: slice, concat, map, filter

  • 返回單個值: reduce, reduceRight, find, findIndex, indexOf, lastIndexOf

字符串方法特點

  • 所有字符串方法都不改變原字符串,因為字符串是不可變的

  • 返回新字符串: toUpperCase, toLowerCase, trim, replace, slice, substring

  • 返回數(shù)組: split

  • 返回布爾值: includes, startsWith, endsWith

常用場景

  1. 數(shù)據(jù)處理: map, filter, reduce

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

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

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

  5. 格式轉(zhuǎn)換: toString, toUpperCase, toLowerCase

到此這篇關(guān)于前端常用字符串/數(shù)組操作方法的文章就介紹到這了,更多相關(guān)前端字符串/數(shù)組操作內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論

永嘉县| 富平县| 汨罗市| 嘉义市| 正阳县| 微博| 永安市| 潼关县| 柏乡县| 达拉特旗| 新疆| 阿坝县| 涿州市| 五寨县| 海城市| 漳州市| 桐乡市| 五大连池市| 平武县| 炎陵县| 漳浦县| 疏附县| 日土县| 于田县| 綦江县| 武平县| 绥德县| 灵璧县| 兴隆县| 晴隆县| 济源市| 板桥市| 即墨市| 大关县| 罗山县| 碌曲县| 滁州市| 上林县| 阳泉市| 宁南县| 阜新|