_.remove() 和 _.pullAt() 之间的 Lodash 区别

Lodash difference between _.remove() and _.pullAt()

lodash _.remove()_.pullAt() 函数有什么区别?

var arr1 = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
_.remove(arr1, function (item) {
  return item == 1
});

var arr2 = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
_.pullAt(arr2, 1);

console.log(arr1.toString() + '\n' + arr2.toString());

// both result to [0,2,3,4,5,6,7,8,9,]

我创建了 fiddle 并阅读了 lodash 网站上的说明 _.remove()

Removes all elements from array that predicate returns truthy for and returns an array of the removed elements

和_.pullAt()

Removes elements from array corresponding to the given indexes and returns an array of the removed elements

有什么区别吗?还是我遗漏了什么?

甚至你的例子也做了不同的事情:

remove按值拼接元素,而pullAt按索引拼接元素。

让我们用不同的数组检查一下 [0, 3, 1, 1, 5]:

  • remove[0, 3, 5] - 所有 1 项已删除
  • pullAt: [0, 1, 1, 5] - arr[1]被拼接

除了按值与 remove 进行比较之外,您还可以编写其他过滤器:

_.remove(arr, item => item % 2); // removes all odd numbers
_.remove(arr, user => user.deleted); // splice deleted users
_.remove(arr, item => item < 5); // and etc.