[英]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. 基本上所有那些pr1,pr2的东西都被声明为const ...我试图使用for循环将它们添加到数组中,但无济于事。 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
: push
接受多个参数,因此您可以在push
时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. 也就是说,拥有如此多的独立变量名称有点代码味道 - 如果可能的话,您可以考虑修改代码,以便在数组中定义
pr
,而不是之后push
。
只需使用Array.prototype.push.apply
:
Array.prototype.push.apply(ar2, [pr1, pr2, pr3, pr4, pr5, pr6]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.