[英]One line push item array and return item
I have this: 我有这个:
getReadableStream() {
const readableStream = new Readable({
read(size) {
return false;
}
});
this.readableStreams.push(readableStream);
return readableStream;
}
however it would be nice if I could push to the array and return the item in the same call, I am looking for this: 但是,如果我可以推送到数组并在同一调用中返回该项目,那就很好了,我正在寻找这个:
getReadableStream() {
return this.readableStreams.push(new Readable({
read(size) {
return false;
}
}));
}
but of course Array.prototype.push
doesn't return the item that was pushed. 但是Array.prototype.push
当然不会返回被推送的项目。 Any way to do this with JavaScript? 用JavaScript可以做到这一点吗? Ideally I don't want to create a new array, keep the original array. 理想情况下,我不想创建一个新数组,保留原始数组。
如果要在一行中执行此操作,则可以使用逗号运算符 :
return this.readableStreams.push(readableStream), readableStream;
An ugly solution would be to override the Arrays prototype: 一个丑陋的解决方案是重写Arrays原型:
Array.prototype.pushAndReturn = function(el){
this.push(el);
return el;
};
So you can do 所以你可以做
return readableStreams.pushAndReturn(new Readable())
Alternatively just create a helper: 或者,只需创建一个助手:
const push = (arr, el) => arr.push(el) && el;
So you can do: 因此,您可以执行以下操作:
return push(readableStreams, new Readable())
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.