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]
:
删除
:[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.
关于javascript - Lodash _.remove() 和 _.pullAt() 之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34070336/