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是一个很好的做法.它消除了依赖关系,迫使您理解您的代码,并且通常更具性能.
Afz*_*ain 56
你可以使用_.union
_.union(scope.index, [val]);
Run Code Online (Sandbox Code Playgroud)
也许_.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)
| 归档时间: |
|
| 查看次数: |
67846 次 |
| 最近记录: |