语法
slice()方法的参数是数组的开始和结束索引
start
start的默认值为0。如果start大于数组的索引范围,slice()方法将返回最后一个元素
end
end
是提取此索引之前的元素,不包括索引 end
在内。因此,索引的最后一个元素不包含在数组的副本中。例如,slice(1,3)
提取是数组的第二个和第三个元素,即从数组的索引 1
开始,包含索引 1
的值到索引 3
之间的数组,但不包含索引为 3
的元素。
功能
1.复制数组
const arrNumbers = [1, 2, 3, 4, 5, 6];
const copyNumbers = arrNumbers.slice();
console.log(copyNumbers); // [ 1, 2, 3, 4, 5, 6 ]
2.从索引n开始的子数组
const arrNumbers = [1, 2, 3, 4, 5, 6];
const copyNumbers = arrNumbers.slice(2);
console.log(copyNumbers); // [ 3, 4, 5, 6 ]
3.类数组对象转换为数组
function transformToArray() {
return Array.prototype.slice.call(arguments);
}
const newArray = transformToArray("1", "2", "3", "4");
console.log(newArray); // [ '1', '2', '3', '4' ]
4.替换字符串中特定索引
String.prototype.append = function (index, value) {
return `${this.slice(0, index)}${value}${this.slice(index)}`;
};
const testString = "新年";
console.log(testString.append(2, "快乐")); // 新年快乐