我想要实现的目的是以某种方式将数组中的所有索引值组合在一起,而不是调用的那个。为了澄清,我写了下面的代码。
第一个document.write
按预期工作,并打印索引的字符串,该字符串与按下的按钮相关联。使用第二个document.write
,我想打印除已点击/选中的所有其他索引元素。如何将所有其他索引元素组合在一起?毋庸置疑,对于你们所有的Javascript大师来说,myarray[!clicked])
在代码中的尝试都行不通。
<html>
<body>
<script>
var myarray = ["button1", "button2", "button3"];
function pushed(clicked) {
for (var i=0; i<myarray.length; i++) {
document.write("the button that has been pushed is" + myarray[clicked]);
document.write("the buttons that have not been pushed are" + myarray[!clicked]);
}
}
</script>
<button onclick="pushed(0)"> Button 1 </button>
<button onclick="pushed(1)"> Button 2 </button>
<button onclick="pushed(2)"> Button 3 </button>
</body>
</html>
您应该打印单击的按钮,然后打印关于未单击的按钮。然后,您可以使用单击的索引和条件将其从正在打印的其他索引中排除。
document.write("the button that has been pushed is" + myarray[clicked]);
document.write("the buttons that have not been pushed are: ");
for (var i = 0; i < myarray.length; i++) {
if (i !== clicked) {
document.write(myarray[i]);
}
}
您不需要遍历数组,只需执行以下操作:
var clicked = myarray[clicked];
var notClicked = myarray.filter(function(item) {
return item !== clicked;
});
document.write('clicked is ' + clicked);
document.write('not clicked are ' + notClicked);
试试这个:
function pushed(clicked) {
document.write("the button that has been pushed is" + myarray[clicked]);
document.write("the buttons that have not been pushed are" + myarray.filter((elt, i) => i !== clicked).join(", "));
}