仅当值不存在时才使用lodash push到数组?

Max*_*ynn 52 javascript arrays angularjs lodash

我正在尝试创建一个数组,如果一个值不存在则添加但是如果值在那里我也想从数组中删除该值.

像Lodash这样的感觉应该可以做这样的事情.

我对您的最佳实践建议感兴趣.

值得指出的是我使用的是Angular.js

*更新*

if (!_.includes(scope.index, val)) {
    scope.index.push(val);
} else {
  _.remove(scope.index, val);
}
Run Code Online (Sandbox Code Playgroud)

flo*_*bon 61

SetES6引入的功能就是这样做的.

var s = new Set();

// Adding alues
s.add('hello');
s.add('world');
s.add('hello'); // already exists

// Removing values
s.delete('world');

var array = Array.from(s);
Run Code Online (Sandbox Code Playgroud)

或者如果你想继续使用常规数组

function add(array, value) {
  if (array.indexOf(value) === -1) {
    array.push(value);
  }
}

function remove(array, value) {
  var index = array.indexOf(value);
  if (index !== -1) {
    array.splice(index, 1);
  }
}
Run Code Online (Sandbox Code Playgroud)

在Lodash上使用vanilla JS是一个很好的做法.它消除了依赖关系,迫使您理解您的代码,并且通常更具性能.

  • “在Lodash上使用香草JS是一个好习惯。” -重新发明轮子永远不是一个好习惯,除非*在对代码进行性能分析之后*确定所讨论的代码是瓶颈。优化非瓶颈不会提高应用程序的性能,并且实际上可能会对总体产生负面影响,因为优化非瓶颈所花费的每一分钟都是没有花在重要事情上的一分钟。通常,最好使用已编写和调试的代码(否则,如果* profiling *不会指导您)。 (4认同)
  • Lodash vs Native性能:https://github.com/you-dont-need/You-Dont-Know-Lodash-Underscore#_each (3认同)
  • @floribon Lodash 使我们能够创建更具可读性的代码,并在钩子下获得出色的性能。无论您的功能是简单还是复杂,我确实看到使用它有更多的优势,并且它也带来了它的复杂性,尽管如此,这是我自己的观点。至于使用 VanillaJS,我必须诚实地说,在我看来,这样想是非常糟糕的。夸张地说,您还可以说使用 VanillaJS 而不是像 Angular/React 这样的框架很棒……现在,将 TypeScript 与 Lodash 一起使用甚至更好,因为它的打字效果比您通常使用的打字要好得多。 (3认同)

Afz*_*ain 56

你可以使用_.union

_.union(scope.index, [val]);
Run Code Online (Sandbox Code Playgroud)

  • 布拉沃,这太棒了。 (2认同)

S.D*_*.D. 5

也许_.pull()可以帮助:

var _ = require('lodash');

function knock(arr,val){ 
   if(arr.length === _.pull(arr,val).length){
      arr.push(val);
   } 
   return arr;
}
Run Code Online (Sandbox Code Playgroud)

改变现有数组,同时删除重复项:

> var arr = [1,2,3,4,4,5];

> knock(arr,4);
[ 1, 2, 3, 5 ]

> knock(arr,6);
[ 1, 2, 3, 5, 6 ]

> knock(arr,6);
[ 1, 2, 3, 5 ]
Run Code Online (Sandbox Code Playgroud)