Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
95 views
in Technique[技术] by (71.8m points)

javascript - Why push does not working with set methond in Map object

So very quick question here which I wasn't able to get sorted when searching google.

I have some code that works which has a Map object this.tweet and a (key,value) of (string,array). I push a value into the array and re-set Map object.

    const newTweet = this.tweet.get(tweetName) || [];
    newTweet.push(time);
    this.tweet.set(tweetName, newTweet);

However, I am a minimalist freak and want a one-liner. When I want to add something to the array, I was wondering why I am not able to do this

this.tweet.set(tweetName, newTweet.push(time));

I keep getting a newTweet.push(time) is not a function error.

Thanks

question from:https://stackoverflow.com/questions/66068551/why-push-does-not-working-with-set-methond-in-map-object

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Look at some documentation for push

The push() method adds one or more elements to the end of an array and returns the new length of the array.

Since you want to pass the array to set you can't use the return value of push.


You could create a completely new array instead:

const newTweet = this.tweet.get(tweetName) || [];
this.tweet.set(tweetName, [...newTweet, time]);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...