JS字符串与数组操作与异同总结

1,202 阅读9分钟

工作中对数组和字符串的操作很频繁,尤其是一些截取操作。字符串和数组的一些操作函数名还有不少相同的,为了不总是混淆,总结下来以备查阅。

一、字符串操作

切割合并截取

split

函数:String.split(separator, ?limit)

功能:使用一个指定的分隔符把一个字符串分割存储到数组

const str = 'jpg|bmp|gif|ico|png';
let arr = str.split('|'); // [jpg, bmp, gif, ico, png]
let arr = str.split('|', 2); // [jpg, bmp] - 第二个参数用来限制数组大小

concat

函数:String.concat(...strings)

功能:将多个字符串依次并在String的后面

'start'.concat(', ', 'hello', ' world') // start, hello world

slice、substring、substr

函数:String.slice(?start, ?end)

  • start:可选。指定子字符串开始位置,默认为0。可以为负数,-1表示最后一位,-2表示倒数第二位。
  • end:可选。指定子字符串结束位置,可以为负数。如果未指定此参数,则表示从start到字符串结束的子字符串。
  • return:返回子字符串,包含从start到end-1的所有字符,长度为end-start。

函数:String.substring(start, ?end)

  • start:必填。非负整数,指定子字符串开始位置。如果start为负数,自动替换为0
  • end:可选。非负整数,指定子字符串结束位置。如果end为负数,自动替换为0
  • return:返回子字符串,包含从start到end-1的所有字符,长度为end-start。

如果start比end大,那么会先交换两个参数再截取字符串

函数:String.substr(from, ?length)

  • from:必填。指定子字符串开始位置。可以为负数,-1表示最后一位,-2表示倒数第二位。
  • length:可选。待选取字符串的长度。0或负数返回空字符串,不指定,则子字符串延续到字符串的最后。
  • return:返回子字符串,包含从start起,截取的length长度的字符串。
'012345'.slice() // 012345
'012345'.substring() // 012345
'012345'.substr() // 012345

'012345'.slice(1) // 12345
'012345'.substring(1) // 12345
'012345'.substr(1) // 12345

'012345'.slice(-2) // 45
'012345'.substring(-2) // 012345	| * 负数替换为0,变成substring(0)
'012345'.substr(-2) // 45

'012345'.slice(1, 3) // 12	| *  位置1到3-1的字符串
'012345'.substring(1, 3) // 12	| * 位置1到3-1的字符串
'012345'.substr(1, 3) // 123	| * 从1起长度为3的字符串

'012345'.slice(3, 1) // ''	| * 从位置3到1,截取不到字符
'012345'.substring(3, 1) // 12	| * start,end互换,变成substring(1,3)
'012345'.substr(3, 1) // 3	| * 从位置3起截取,长度为1

'012345'.slice(-3, -1) // 34	| * 倒数第3位到(倒数第1位-1)的字符串
'012345'.substring(-3, -1) // ''	| * 负数替换为0,变成substring(0, 0)
'012345'.substr(-3, -1) // ''	| * length为负数,没有长度,返回空字符串

小结:

  1. slice, substring根据位置截取字符串;substr根据长度截取。
  2. substringstart/end的有效值为非负整数,slicestart/end, substrfrom可以为负数。
  3. 第二个参数不提供(end, length),则截取到字符串末尾。
  4. 只有substring会根据大小自动调整start, end的先后,以截取到有效字符串。

查找替换

indexOf、lastIndexOf

函数:String.indexOf(searchString, ?position), String.lastIndexOf(searchString, ?position) 功能:indexOf从字符串开始位置向后查找指定字符串的位置,lastIndexOf相反,从字符串尾部向前查找

  • searchString:要查找的字符串
  • position:从这个位置开始查找,不从开始或结束位置查找。非负整数。
  • return:找到字符串则返回位置索引,否则返回-1
'hello world'.indexOf('o') // 4
'hello world'.indexOf('o', 5) // 7	| * 从空格处(index=5)开始向后查找
'hello world'.lastIndexOf('o', 7) // 7
'hello world'.lastIndexOf('o', 5) // 4	| * 从空格处(index=5)开始向前查找

charAt

函数:String.charAt(index)

功能:返回指定位置的字符。字符串中第一个字符的下标是0。如果参数 index 不在 0 与 string.length 之间,该方法将返回一个空字符串。

  • index: 可选,默认为0,要选取字符的下标位置,非负整数。
'0123456'.charAt(4) // 4
'0123456'.charAt(10) // ''

charCodeAt

函数:String.charCodeAt(index) 功能:返回指定位置的字符的 Unicode 编码。这个返回值是 0 - 65535 之间的整数。如果参数 index 不在 0 与 string.length 之间,该方法将返回NaN(因为没找到字符串,空字符串无法转换位数字)。

'0123456'.charCodeAt(4) // 52
'0123456'.charCodeAt(-1) // NaN
'0123456'.charCodeAt(10) // NaN

replace

函数:String.replace(searchValue, replaceValue)

  • searchValue: 被替换的字符串,可以是正则表达式
  • replaceValue: 替换的字符串
'bone, alone, phone'.replace('one', 1) // b1, alone, phone
'bone, alone, phone'.replace(/one/g, 1) // b1, al1, ph1

trim

函数:String.trim() 功能:去除字符串首尾空格

trim在ES5已定义,且大多数浏览器已支持,不再需要自己实现。详见:trim on MDN

'  hello   '.trim() // 'hello'

二、数组操作

数组整体操作

join

函数:Array.join(?separator)

功能:通过指定的分隔符将数组项连接合并为一个字符串,参数不传则默认为","

const arr = ['jpg', 'bmp', 'gif', 'ico', 'png']
let str = arr.join('|') // jpg|bmp|gif|ico|png

reverse

功能:将函数项颠倒顺序,会改变原数组

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

concat

功能:将多个数组合并,不改变原数组

const ary = ['cat']
const newary = ary.concat(['hat'], ['bat', 'fat'])
console.log(newary) // ["cat", "hat", "bat", "fat"]

数组项操作

indexOf, lastIndexOf

功能:indexOf从前往后查找第一个匹配的数组项索引,lastIndexOf相反

const ary = ["cat", "hat", "cat", "fat"]
const index = ary.indexOf('cat') // 0
const lastIndex = ary.lastIndexOf('cat') // 2

push

功能:数组尾部插入一个项,会改变原数组。返回值为插入后的数组长度。

const ary = ['head', 'tail']
const length = ary.push('hello')
console.log(ary) // ['head', 'tail', 'hello']
console.log(length) // 3

pop

功能:数组尾部移除一个项,会改变原数组。返回值为移除的项。

const ary = ['head', 'tail']
const item = ary.pop()
console.log(ary) // ['head']
console.log(item) // 'tail'

unshift

功能:数组头部插入一个项,会改变原数组。返回值为插入后的数组长度。

const ary = ['head', 'tail']
const length = ary.unshift('hello')
console.log(ary) // ['hello','head', 'tail']
console.log(length) // 3

shift

功能:数组头部移除一个项,会改变原数组。返回值为移除的项。

const ary = ['head', 'tail']
const item = ary.shift()
console.log(ary) // ['tail']
console.log(item) // 'head'

slice

函数:Array.slice(?start, ?end)

功能:数组项的截取,生成子数组。

  • start:可选。指定数组元素开始位置,默认为0。可以为负数,-1表示最后一位,-2表示倒数第二位。
  • end:可选。指定子数组元素结束位置,可以为负数。如果未指定此参数,则表示从start到字符串结束的子字符串。
  • return:返回子字符串,包含从start到end-1的所有元素,数组长度为end-start。
const ary1 = [0,1,2,3,4,5].slice() // [0,1,2,3,4,5]
const ary2 = [0,1,2,3,4,5].slice(3) // [3,4,5]
const ary3 = [0,1,2,3,4,5].slice(3, 5) // [3,4]
const ary4 = [0,1,2,3,4,5].slice(3, -1) // [3,4]	| * end = -1 + 6 = 5, 倒数第一项
const ary5 = [0,1,2,3,4,5].slice(-2, -1) // [4]

splice

函数:Array.splice(start, ?deleteCount, ...items)

功能:可以对数组进行添加删除,间接实现替换功能。会改变原数组。

  • start:起始操作索引(删除或添加项的开始位置,删除时包含start所在项)
  • deleteCount:从start开始,要删除的项的个数,非负整数。若不指定,则删除从start到数组尾的所有项
  • items:要添加的数组项,可以为多个
  • return:返回被删除的元素组成的数组
let ary = [0, 1, 2, 3, 4, 5]
let res = ary.splice(2) // 从2的位置起,向后删除所有项
console.log(ary, res) // ary = [0, 1], res = [2, 3, 4, 5]

ary = [0, 1, 2, 3, 4, 5]
res = ary.splice(2, 1) // 从2的位置起,删除1个项
console.log(ary, res) // ary = [0, 1, 3, 4, 5], res = [2]

ary = [0, 1, 2, 3, 4, 5]
res = ary.splice(2, 3) // 从2的位置起,删除3个项
console.log(ary, res) // ary = [0, 1, 5], res = [2, 3, 4]

ary = [0, 1, 2, 3, 4, 5]
res = ary.splice(2, 1, 'hello') // 从2的位置起,删除1个项, 同时在2的位置添加一个项(间接实现替换功能)
console.log(ary, res) // ary = [0, 1, 'hello', 3, 4, 5], res = [2]

ary = [0, 1, 2, 3, 4, 5]
res = ary.splice(2, 3, 'hello') // 从2的位置起,删除3个项, 同时在2的位置添加一个项
console.log(ary, res) // ary = [0, 1, 'hello', 5], res = [2, 3, 4]

ary = [0, 1, 2, 3, 4, 5]
res = ary.splice(2, 1, 'hello', 'world') // 从2的位置起,删除1个项, 同时在2的位置依次添加多个项
console.log(ary, res) // ary = [0, 1, 'hello', 'world', 3, 4, 5], res = [2]

ary = [0, 1, 2, 3, 4, 5]
res = ary.splice(2, 3, 'hello', 'world') // 从2的位置起,删除3个项, 同时在2的位置依次添加多个项
console.log(ary, res) // ary = [0, 1, 'hello', 'world', 5], res = [2, 3, 4]

迭代操作

sort

功能:按照数组项的字符的unicode排序,如果不是字符串,调用toString转为字符串。

const ary = [1, 2, 10, 3]
ary.sort()
console.log(ary) // [1, 10, 2, 3]	| * 10转成字符串'10'

forEach

功能:数组遍历

['a', 'b', 'c'].forEach(function(item, index, array) {
    console.log(item, index, array)
    // a 0 ['a', 'b', 'c'];
    // b 1 ['a', 'b', 'c']; 
    // c 2 ['a', 'b', 'c'];
})

map

功能:遍历数组各项,并返回对项进行处理后的数组

const ary = ['a', 'b', 'c'].map(function(item, index, ary) {
  return item.charCodeAt(0)
})
console.log(ary) // [97, 98, 99]

filter

功能:遍历数组各项,并返回符合条件的数组项组成的数组

const ary = [1, 2, 3, 10, 21].map(function(item, index, ary) {
  return item < 10
})
console.log(ary) // [1, 2, 3]

every, some

功能:

  • every: 遍历数组各项,每个项都符合条件,则返回true,否则返回false
  • some:遍历数组各项,一旦找到符合条件的项,则返回true,停止遍历,否则返回false
let res = [1, 2, 3, 10, 21].every(function(item, index, ary) {
 	return item < 100
})
console.log(res) // true

res = [1, 2, 3, 10, 21].some(function(item, index, ary) {
	console.log(item) // 1 只执行了一次
 	return item < 100
})
console.log(res) // true

res = [1, 2, 3, 10, 21].some(function(item, index, ary) {
	console.log(item) // 1 2 3 10 21 遍历了全部
 	return item > 100
})
console.log(res) // false

reduce, reduceRight

函数:array.reduce(function(total, currentValue, currentIndex, arr), initialValue)

功能:聚合数组项,根据聚合函数生成最后结果。reduce从第一个元素开始,从左向右聚合,reduceRight相反

let res = [1, 2, 3, 4, 5].reduce(function(a, b) {
  return a + b
})
console.log(res) // 1 + 2 + 3 + 4 + 5 = 15

res = [1, 2, 3, 4, 5].reduce(function(a, b) {
  return a + b
}, 10) // 初始值
console.log(res) // 10 + 1 + 2 + 3 + 4 + 5 = 25

res = [1, 2, 3, 4, 5].reduce(function(a, b) {
  return a - b
})
console.log(res) // 1 - 2 - 3 - 4 - 5 = -13

res = [1, 2, 3, 4, 5].reduceRight(function(a, b) {
  return a - b
})
console.log(res) // 5 - 4 - 3 - 2 - 1 = -5

res = [1, 2, 3, 4, 5].reduceRight(function(a, b) {
  return a - b
}, 1) // 初始值
console.log(res) // 1 - 5 - 4 - 3 - 2 - 1 = -14

小结

  • 会改变原数组的操作:reverse, sort, splice, push, pop, shift, unshift

三、字符串与数组的一些同名操作

slice

const str = '012345'.slice(1,3) // '12'
const ary = [0,1,2,3,4,5].slice(1,3) // [1,2]

concat

const str = 'start'.concat(', ', 'hello', ' world') // start, hello world
const ary = ['start'].concat([',', ' hello'], ['world']) // ['start', ',', ' hello', 'world']

indexOf, lastIndexOf

const index1 = 'hello world'.indexOf('o') // 4
const index2 = ['hello''world'].indexOf('world') // 1
const index3 = 'hello world'.lastIndexOf('o') // 7
const index4 = ['hello''world'].lastIndexOf('world') // 1