繁体   English   中英

返回lodash中索引n处没有元素的数组

[英]Return array without element at index n in lodash

现在我有这个功能:

function without(array, index) {
    array.splice(index, 1);
    return array;
}

我认为这将是lodash会有一个实用工具,但看起来不是。

有这个功能允许我做一个我可以链的单线程:

var guestList = without(guests, bannedGuest).concat(moreNames);

没有引入谓词函数,使用lodash无法实现这一目标?

_.without已经存在。 或者,您也可以使用_.pull ,它会改变给定的参数数组。

var guests = ['Peter', 'Lua', 'Elly', 'Scruath of the 5th sector'];
var bannedGuest = 'Scruath of the 5th sector';
var bannedGuests = ['Peter', 'Scruath of the 5th sector'];

console.debug(_.without(guests, bannedGuest )); // ["Peter", "Lua", "Elly"]

不直接支持禁止一组客人,但我们可以轻松解决这个问题:

// banning an array of guests is not yet supported, but we can use JS apply:
var guestList = _.without.apply(null, [guests].concat(bannedGuests));
console.debug(guestList); // ["Lua", "Elly"]

// or if you are feeling fancy or just want to learn a new titbit, we can use spread:
guestList = _.spread(_.without)([guests].concat(bannedGuests));
console.debug(guestList); // ["Lua", "Elly"]

的jsfiddle

或者,您也可以查看_.at_.pullAt ,它们具有相似的行为,除了取数组索引而不是要删除的对象。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM