实例1:
let arr = [1, 2, 3, 4, 5];
console.log(arr.slice(0, 2)); //[1,2]
let str = "12345";
console.log(str.slice(0, 2)); //12
实例2:
当slice中只有一个参数,就表示以当前参数为下标开始截取
let arr = [1, 2, 3, 4, 5];
console.log(arr.slice(2)); //[3,4,5]
let str = "12345";
console.log(str.slice(2)); //345
实例3:
当slice参数为负数的时候,就从最后一个-1开始倒数过来,找到start开始截取的位置,然后开始截取
let arr = [1, 2, 3, 4, 5];
console.log(arr.slice(-2)); //[4,5]
let str = "12345";
console.log(str.slice(-2)); //45
let arr = [1, 2, 3, 4, 5];
console.log(arr.slice(-2, -1)); //[4]
let str = "12345";
console.log(str.slice(-2, -1)); //4
实例如下:
let str = "12345";
console.log(str.substr(0, 2)); //12
console.log(str.substr(2)); //345
实例1:
let str = "12345";
console.log(str.substring(1, 2)); //2
console.log(str.substring(2)); //345
实例2:
substring中参数为负数会用0替换,而substr参数为负数,是从结尾开始的
let str = "12345";
console.log(str.substring(4, 2)); //34
console.log(str.substring(-2)); //12345
console.log(str.substr(-2)); //45
实例1:
let arr = [1, 2, 3, 4, 5];
let b = arr.splice(0, 2);
console.log(b); // [1,2]
console.log(arr); //[3,4,5]
实例2:
let arr = [1, 2, 3, 4, 5];
let b = arr.splice(1, 2);
console.log(b); // [2, 3]
console.log(arr); //[1,4,5]
实例3
splice删除和插入
let arr = [1, 2, 3, 4, 5];
let b = arr.splice(1, 2, "new");
console.log(b); // [2, 3]
console.log(arr); //[1,'new',4,5]
split() 方法用于把一个字符串分割成字符串数组
split可以放两个参数,第一个参数表示分隔符,必选的;第二个参数表示返回数组的最大长度
let str = "123,123,123,123,123";
let a = str.split(",");
let b = str.split(",", 2);
console.log(a); // ["123", "123", "123", "123", "123"]
console.log(b); // ["123", "123"]