ES6之常用小技巧 方法 和 属性

154 阅读2分钟

删除最后一个数字

 1.let str = "1553"; 
     Number(str.substring(0, str.length - 1));

2.console.log(1553 / 10 | 0) // Result: 155
    console.log(1553 / 100 | 0) // Result: 15
    console.log(1553 / 1000 | 0) // Result: 1

数组截断

let array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
array = array.slice(0, 4);
console.log(array); // Result: [0, 1, 2, 3]

如何从数组中移除一个特定的项

思路:首先,使用indexOf查找要删除的数组元素的索引(index),然后使用splice方法删除该索引所对应的项。

splice()是一个非纯函数,通过删除现有元素和/或添加新元素来更改数组的内容。const array = [2, 5, 9]

const index = array.indexOf(5)
if (index > -1) {
  array.splice(index, 1)
}

console.log(array)
// [ 2, 9 ]
splice的第二个参数是要删除的元素数量。注意,splice会在适当的位置修改数组,并返回一个包含已删除元素的新数组。
接着,我们可以来完善一下。下面有两个函数,第一个函数仅删除一个匹配项(即从[2,5,9,1,5,8,5]中删除第一个匹配项5),而第二个函数则删除所有匹配项:
// 仅删除第一个匹配项
function removeItemOnce (arr, value) {
  let index = arr.indexOf(value)
  if (index > -1) {
    arr.splice(index, 1)
  }
  return arr
}

// 删除所有匹配项
function removeItemAll (arr, value) {
  let i = 0
  while(i < arr.length) {
    if (arr[i] === value) {
      arr.splice(i, 1)
    } else {
      ++i
    }
  }
}
复制代码
删除数组中索引i处的元素:
删除数组中索引i处的元素:
array.splice(i, 1)

如果你想从数组中删除值为number的每个元素,可以这样做:
for (let i = array.length - 1; i>=0; i--) {
  if (array[i] === number) {
    array.splice(i, 1)
  }
}
复制代码
如果你只想使索引i处的元素不再存在,但又不想更改其他元素的索引:
delete array[i]

Set && Map

Set处理并集(Union)、交集(Intersect)和差集(Difference)

let a = new Set([1, 2, 3]);
let b = new Set([4, 3, 2]);

// 并集
let union = new Set([...a, ...b]);
// Set {1, 2, 3, 4}

// 交集
let intersect = new Set([...a].filter(x => b.has(x)));
// set {2, 3}

// (a 相对于 b 的)差集
let difference = new Set([...a].filter(x => !b.has(x)));
// Set {1}

const map = new Map([ ['name', '张三'], ['title', 'Author'] ]);

map.has('name') // true

 map.get('name') // "张三"