【JS】splice函数用法-2. 用法

时间:2024-10-29 15:28:03

2.1 删除

const months = ['1', '2', '3', '4'];
months.splice(1, 0);	//['1', '2', '3', '4']

const months = ['1', '2', '3', '4'];
months.splice(1, 1);	//['1', '3', '4']

const months = ['1', '2', '3', '4'];
months.splice(1, 2);	//['1', '4']

2.2 替换

const months = ['1', '2', '3', '4'];
months.splice(1, 1, 'x');	//['1', 'x', '3', '4']

const months = ['1', '2', '3', '4'];
months.splice(1, 2, 'y');	//['1', 'y', '4']

const months = ['1', '2', '3', '4'];
months.splice(1, 2, , 'x', 'y');	//['1', 'x', 'y', '4']

2.3 插入

const months = ['1', '2', '3', '4'];
months.splice(1, 0, 'x');	//['1', 'x', '2', '3', '4']