简体   繁体   中英

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. Any way to do this with 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:

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())

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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