Javascript - 指定数组中的所有其他索引元素(除了被调用的元素之外)

时间:2018-03-04 15:29:32

标签: javascript arrays

我想要实现的目的是以某种方式将数组中的所有索引值组合在一起,而不是调用的那个。为了澄清,我写了下面的代码。

第一个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>

3 个答案:

答案 0 :(得分:1)

您应该打印单击的按钮,然后打印关于未单击的按钮。然后,您可以使用单击的索引和条件将其从正在打印的其他索引中排除。

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]);       
    }
}

答案 1 :(得分:1)

您不需要遍历数组,只需执行:

var clicked = myarray[clicked];
var notClicked = myarray.filter(function(item) {
    return item !== clicked;
});
document.write('clicked is ' + clicked);
document.write('not clicked are ' + notClicked);

答案 2 :(得分:0)

试试这个:

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(", "));
}