简体   繁体   中英

How can I refactor adding const object names into the array?

My code is working, but it looks very creepy.

ar2.push(pr1);ar2.push(pr2);ar2.push(pr3);ar2.push(pr4);ar2.push(pr5);ar2.push(pr6);

basically all those pr1, pr2 things are declared const... I was trying to add them to the array using a for loop, to no avail. Is there any way to do a one liner for this?

push accepts multiple parameters, so you can just list them all when you push :

ar2.push(pr1, pr2, pr3, pr4, pr5, pr6);

That said, it's a bit of a code smell to have so many standalone variable names - if possible, you might consider modifying your code such that the pr s are defined in an array to begin with, rather than push ing afterwards.

只需使用Array.prototype.push.apply

Array.prototype.push.apply(ar2, [pr1, pr2, pr3, pr4, pr5, pr6]);

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