字符串

substring、substr

都带str,所以是截取字符串的方法,二者皆返回一个副本不改变原字符串

  1. var str = '0123456789';
  2. console.log( str.substring(1) ); // 123456789。第二个参数留空则默认截取到结束
  3. console.log( str.substr(1) ); // 123456789
  4. console.log( str.substring(2, 5) ); // 234。区间为[2, 5)
  5. console.log( str.substr(2, 5) ); // 23456。区间为[2, 2+5-1]
  6. console.log( str.substr(-4) ); // 6789。截取后四位
  7. console.log( str ); // 0123456789。原字符串并没有发生变化
  1. substring($1, $2) 比较长,因此截取得短,区间表示为 [$1, $2)$1 表示起始下标,$2 表示截止下标
  2. substr($1, $2) 比较短,因此截取得长,区间表示为 [$1, $1+$2-1]$1 表示起始下标,$2 表示截多少个
  3. 两者的 $2 留空则都默认截取到结束。
  4. substr 短小精悍,$1 竟然还能接受负数,返回末尾的$1 位,此时$2不生效。

    数组

    slice和splice

    针对数组,但是字符串也能使用slice。
    slice不改变原数组
    splice改变原数组;(直接在数组上操作的的还有pop/push/shift/unshift/sort/reverse/concat) ```javascript var arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];

console.log( arr.slice(1) ); // [1, 2, 3, 4, 5, 6, 7, 8, 9] console.log( arr ); // [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],不改变数组。 console.log( arr.splice(1) ); // [1, 2, 3, 4, 5, 6, 7, 8, 9] console.log( arr ); // [0]。被 splice 砍剩下的

arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]; // 重新补血

console.log( arr.slice(2, 5) ); // [2, 3, 4] console.log( arr.splice(2, 5) ); // [2, 3, 4, 5, 6] console.log( arr ); // [0, 1, 7, 8, 9]

arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]; // 重新补血

console.log( arr.slice(5) ); // [5, 6, 7, 8, 9] console.log( arr.splice(5) ); // [5, 6, 7, 8, 9] console.log( arr ); // [0, 1, 2, 3, 4]

arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]; // 重新补血

console.log( arr.slice(-3) ); // [7, 8, 9] console.log( arr.splice(-3) ); // [7, 8, 9] console.log( arr ); // [0, 1, 2, 3, 4, 5, 6]

  1. <a name="E5JuL"></a>
  2. #### 区分tip
  3. ```javascript
  4. // 将伪数组转数组,不能伤害 arguments 本身,因此 slice 显然就是返回副本
  5. Array.prototype.slice.call(arguments);
  1. slice($1, $2) 并非在原数组上操作,而是返回被切部分的副本。区间表示为[$1, $2)$1 是起始下标,$2 是截止下标
  2. splice($1, $2) 直接在原数组上操作,返回被切掉的部分。区间表示为 [$1, $1+$2-1]$1 是起始下标, $2 是切多少个
  3. 两者的 $2 留空则都默认截取到结束。
  4. 最后的最后,就是由于二者拼写长度仅相差一个字母,因此二者的 $1 均能接受负数。

slice第二个参数为负数时

  1. let msg = 'hello world';
  2. let str = msg.slice(1,-1); //截取msg从index=1,到msg的最后一个字符串,但不包括最后一个字符串
  3. console.log(msg); //hello world
  4. console.log(str); // ello worl
  5. //数组也是一样的
  6. let arr = [11,22,33,44,55,66];
  7. let newArr = arr.slice(2,-2); //从数组中截取下标为2开始,到数组的倒数第二个(但不包括他),返回新数组;
  8. console.log(arr);
  9. console.log(newArr);