我有以下代码:
process.on("message", function(data){
if(data.cmd === "BROADCAST_TO_WORKER"){
io.sockets.emit("SERVER_MESSAGE", { message: data.message, reload: data.reload, player_id : data.player_id });
}
});
我想在数组的开头多次添加var foo = 'foo'
var bar = 'bar'
var arr = [1,2,3]
,在数组的末尾添加foo
。每个元素添加的次数应该是动态的,结果数组应该是这样的:
bar
有没有比为每个元素使用循环更好的方法?如果需要,我可以使用lodash。
答案 0 :(得分:5)
如果更好意味着更短,是的还有一种方法:
forloop
答案 1 :(得分:1)
试试这个push
方法。 Array#unshift()
在数组的开头添加了值。var foo = 'foo'
var bar = 'bar'
var arr = [1,2,3]
for(var i=0; i<(Math.random() * 5); i++){
arr.unshift(foo)
}
for(var i=0; i<(Math.random() * 5); i++){
arr.push(bar)
}
console.log(arr)
添加了数组的结尾
<!-- HEADER -->
<header id="header" class="header-left">
<div class="header-inner clearfix">
<!-- LOGO -->
<div id="logo" class="logo-left">
<a href="index.html">
<img id="dark-logo" src="files/uploads/logo_dark.png" srcset="files/uploads/logo_dark.png 1x, files/uploads/logo_dark@2x.png 2x" alt="Logo Dark">
<img id="light-logo" src="files/uploads/logo_light.png" srcset="files/uploads/logo_light@2x.png 1x, files/uploads/logo_light@2x.png 2x" alt="Logo Light">
</a>
</div>
<!-- MAIN NAVIGATION -->
<div id="menu" class="clearfix">
<div class="menu-actions">
<div class="menu-toggle"><span class="hamburger"></span></div>
</div> <!-- END .menu-actions -->
<div id="menu-inner">
<nav id="main-nav">
<ul>
<li><a href="index.html">xxx</a>
</li>
<li><a href="#">xxx</a>
<ul class="sub-menu">
<li><a href="xxx.html">xxx</a></li>
<li><a href="xxx.html">xxxx</a></li>
<li><a href="xxx.html">xxx</a></li>
</ul>
</li>
</ul>
</nav>
</div>
</div>
</div>
<span class="pseudo-close header-close"></span>
</header>
&#13;
答案 2 :(得分:0)
function pushToBeginning(arr, str, count){
while(count--){
arr.unshift(str);
}
}
function pushToEnd(arr, str, count){
while(count--){
arr.push(str);
}
}
let arr = [1, 2, 3];
pushToBeginning(arr, 'Foo', 3);
pushToEnd(arr, 'Bar', 2);
console.log(arr);
答案 3 :(得分:0)
或类似的东西。
<android.support.design.widget.TextInputLayout
android:textColorHint="#404040" // Change color as per your wish
android:layout_width="match_parent"
android:layout_height="wrap_content">
<EditText
android:layout_width = "match_parent"
android:layout_height = "wrap_content"
android:hint ="Email"
android:maxLines="1"
android:textColor="#000000" />
</android.support.design.widget.TextInputLayout>
<android.support.design.widget.TextInputLayout
android:layout_marginTop="10dp"
android:textColorHint="#404040" // Change color as per your wish
android:layout_width="match_parent"
android:layout_height="wrap_content">
<EditText android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/passwordText"
android:hint="Password"
android:maxLines="1"
android:textColor="#000000"
android:inputType="textPassword"/>
</android.support.design.widget.TextInputLayout>