字符串

substring

形式:substring(index1, index2)

var str = "0123456789";
console.log(str.substring(1, 5)); // "1234"
console.log(str.substring(8, 4)); // "4567"
console.log(str.substring(1)); // "123456789"
console.log(str.substring(-2, 6)); // "012345"
console.log(str); // "0123456789"

substr

形式:substr(start, length)

var str = "0123456789";
console.log(str.substr(1, 5)); // "12345"
console.log(str.substr(4)); // "456789"
console.log(str.substr(-3)); // "789"
console.log(str.substr(4, 0)); // ""
console.log(str.substr(4, -2)); // ""
console.log(str); // "0123456789"

数组

splice

形式:substr(start, length, *args)

var arr = [0,1,2,3,4,5,6,7,8,9];
console.log(arr.splice(2, 3, 12, 13)); // 返回删除的元素 [2,3,4]
console.log(arr); // [0,1,12,13,5,6,7,8,9]
console.log(arr.splice(2, 3)); // [12,13,5]
console.log(arr); // [0,1,6,7,8,9]
console.log(arr.splice(2, 0, 22, 23)); // 返回[],没有删除任何元素
console.log(arr); // [0,1,22,23,6,7,8,9]

数组&字符串

slice

形式:slice(start, stop)

var str = "0123456789";
var arr = [0,1,2,3,4,5,6,7,8,9];
console.log(str.slice(1, 6)); // "12345"
console.log(arr.slice(1, 6)); // [1,2,3,4,5]
console.log(str.slice(2)); // "23456789"
console.log(arr.slice(2)); // [2,3,4,5,6,7,8,9]
console.log(str.slice(3,3)); // ""
console.log(arr.slice(3,3)); // []
console.log(str.slice(6,5)); // ""
console.log(arr.slice(6,5)); // []
console.log(str.slice(6,-1)); // "678"

参考文章链接

发表回复