split, splice和slice

split, splice和slice

  • String.prototype.split()
  • Array.prototype.splice()
  • Array.prototype.slice()

一直记不得这三个哪个是哪个,加强记忆一下。
以下摘录自MDN。

String.prototype.split()

split() 方法使用指定的分隔符字符串将一个String对象分割成子字符串数组,以一个指定的分割字串来决定每个拆分的位置。

语法: str.split(separator, limit)

1
2
3
4
5
6
7
8
9
10
11
12
13
const str = 'The quick brown fox jumps over the lazy dog.';

const words = str.split(' ');
console.log(words[3]);
// expected output: "fox"

const chars = str.split('');
console.log(chars[8]);
// expected output: "k"

const strCopy = str.split();
console.log(strCopy);
// expected output: Array ["The quick brown fox jumps over the lazy dog."]

split() 是把一个字符串分割成数组,通常结合 join() 使用, join() 是将一个数组中的所有元素拼接成一个字符串。
join 也是可以传入一个字符串用于拼接时插入在数组元素之间。

Array.prototype.splice()

splice() 方法通过删除或替换现有元素或者原地添加新的元素来修改数组, 并以数组形式返回被修改的内容。此方法会改变原数组。

语法: array.splice(start, deleteCount, item1, item2, ...)

1
2
3
4
5
6
7
8
9
10
const months = ['Jan', 'March', 'April', 'June'];
months.splice(1, 0, 'Feb');
// inserts at index 1
console.log(months);
// expected output: Array ["Jan", "Feb", "March", "April", "June"]

months.splice(4, 1, 'May');
// replaces 1 element at index 4
console.log(months);
// expected output: Array ["Jan", "Feb", "March", "April", "May"]

Array.prototype.slice()

slice() 方法返回一个新的数组对象,这一对象是一个由 beginend 决定的原数组的浅拷贝(包括 begin,不包括end)。原始数组不会被改变。

语法: arr.slice(begin, end)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
const animals = ['ant', 'bison', 'camel', 'duck', 'elephant'];

console.log(animals.slice(2));
// expected output: Array ["camel", "duck", "elephant"]

console.log(animals.slice(2, 4));
// expected output: Array ["camel", "duck"]

console.log(animals.slice(1, 5));
// expected output: Array ["bison", "camel", "duck", "elephant"]

console.log(animals.slice(-2));
// expected output: Array ["duck", "elephant"]

console.log(animals.slice(2, -1));
// expected output: Array ["camel", "duck"]

评论