slice-substring-substr-split-splice

一、字符串
slice(startIndex, endBeforeIndex)
  endBeforeIndex < 0,则 endBeforeIndex 为 负数,第二个参数为字符串长度加上负值,之后如果第二个参数大于第一个参数,则返回空字符串。

substring(startIndex, endBeforeIndex)
  endBeforeIndex < 0,则 第二个参数会变成 0,可以看成会变成第一个参数,startIndex 为第二个参数,如果 startIndex 也为 <= 0,则返回字符串。

subStr(startIndex, length)
  如果第二个参数省略,默认为字符串长度;
  startIndex < 0,则 startIndex 的值可以由字符串长度加上 startIndex;或直接从后面算起。

split(separator, limit)
  将字符串分割成数组,separator 为分割的字符,不会返回数组中;limit 是返回的数组长度,可以省略。返回的数组长度比可匹配的 separator 多 1;
  separator 前后一定会返回一个数组元素,如果 separator 的后面没有元素了,则以空字符串 '' 表示。

二、数组
splice(array.splice(index, howmany, item1,.....,itemX))
  用于添加或删除数组中的元素。注意:这种方法会改变原始数组。
  一个参数执行的是删除,参数一是开始删除下标,删除个数从开始下标开始到结束;
  两个参数执行的是删除,参数一是开始删除下标,参数二是删除的个数;
  三个参数时,如果第二个参数为 0, 则在下标 index 处把第三个参数后面的元素添加到数组中;如果第二个参数不为 0, 则在下标 index 处后开始删除 howmany 个参数,再把 item 各项添加到 index 下标后。

//         012345678
var str = "HTMLCSSJS";

console.log('slice(startIndex, endBeforeIndex)');
console.log( str.slice(1) ); // TMLCSSJS
console.log( str.slice(1, 3) ); // TM
console.log( str.slice(1, -2) ); // str.slice(1, 7); —— TMLCSS
console.log( str.slice(5, -6) ); // str.slice(5, 3); —— 空字符串

console.log('substring(startIndex, endBeforeIndex)');
console.log( str.substring(1) ); // TMLCSSJS
console.log( str.substring(1, 3) ); // TM
console.log( str.substring(1, -2) ); // substring(1, 0) ——> subtring(0, 1); —— H
console.log( str.substring(-1, -2) ); // 空字符串

console.log('substr(startIndex, length)');
console.log( str.substr(1) ); // TMLCSSJS
console.log( str.substr(-1) ); // substr(8); —— S
console.log( str.substr(-2, 4) ); // substr(7, 4); —— JS
console.log( str.substr(-7, 4) ); // substr(2, 4); —— MLCS
console.log('\n');

console.log('str.split(separator, limit)');
console.log( str.split('') ); // (9) ['H', 'T', 'M', 'L', 'C', 'S', 'S', 'J', 'S']
console.log( str.split('', 4) ); // (4) ['H', 'T', 'M', 'L']
console.log( str.split('S') ); // (4) ['HTMLC', '', 'J', '']
console.log('\n');

var arr = [1, 2, 3, 4, 5];
console.log( arr.splice(1, 2) );  // (2) [2, 3] 从下标 1 开始 删除两个元素。返回被删除元素组成的数组
console.log( arr ); // (3) [1, 4, 5]
console.log( arr.splice(2) ); // [5]
console.log( arr ); // (2) [1, 4]
console.log('\n');

var arr2 = [1, 2, 3, 4, 5, 6, 7];
console.log( arr2.splice(1, 0, 123, 'happy') ); // []
console.log( arr2 ); // (9) [1, 123, 'happy', 2, 3, 4, 5, 6, 7]
console.log('\n');

var arr3 = [1, 2, 3, 4, 5, 6, 7];
console.log( arr3.splice(1, 2, 123, 'happy') ); // (2) [2, 3]
console.log( arr3 ); // (9) [1, 123, 'happy', 2, 3, 4, 5, 6, 7]
console.log('\n');

 

posted @ 2022-04-12 19:11  し7709  阅读(26)  评论(0编辑  收藏  举报