2018-6-2_《JS操作数组 (整理)》

/*
    影响原数组,“有味”方法(9个)有:
   1. splice()  向/从数组中添加/删除项目
   2. sort()
   3. pop()
   4. shift()
   5. push()
   6. unshift()
   7. reserve()
   8. copyWithin()   ES6
   9. fill()         ES6 */

一. splice // 1. 删除元素。 办法:只需splice()掉要删除的元素就行 let arr = [1, 2, 3, 4, 5, 6, 7]; let item = arr.splice(0, 3); //从0标开始,取3个长度为截断处;欲‘截断’部分; console.log(item); //[1,2,3] console.log(arr); //“截余”部分;[4,5,6,7]
// 2. 删除并添加。 办法:只需添加splice()第三参数 let arr = [1, 2, 3, 4, 5, 6, 7]; let item = arr.splice(0, 3, 'foo','bar'); //splice若有第三个参数,作用是替换“被删除”的元素的项; console.log(item); // [1,2,3] console.log(arr); //被影响的原数组: ['foo','bar',4,5,6,7] // 3-1. 不删除只添加(加于前)。办法:只需splice()第一、第二参数为0 let arr = [1, 2, 3, 4, 5, 6, 7]; let item = arr.splice(0, 0, 'foo','bar'); // 只需splice()第一、第二参数为0 console.log(item); // "截掉"的元素为[],一个也不截掉 console.log(arr); //['foo','bar',1,2,3,4,5,6,7] //3-2. 不删除只添加。(加于后) 办法:只需splice()第一参数为-1,第二参数为0

let arr = [1, 2, 3, 4, 5, 6, 7];
let item = arr.splice(-1, 0, 'foo','bar'); //添加于最后,只需从“负标”开始
console.log(item); // []
console.log(arr); // [1,2,3,4,5,6,7,'foo','bar']





/*不影响原数组方法, “纯真”方法(8个)有: 
  1. slice()
  2. join()
  3. toLocateString()
  4. toString()
  5. cancat()
  6. indexOf()
  7. lastIndexOf()
  8. includes() ES7 */

console.log('待续...');

  

猜你喜欢

转载自www.cnblogs.com/beesky520/p/9124834.html
今日推荐