简体   繁体   English

如何使按钮更改Javascript数组位置?

[英]How can I make a button change Javascript array positions?

I need to make a button that is able to replace array positions(text). 我需要制作一个能够替换数组位置(文本)的按钮。 eg array position 3 needs to become array position 1. It only has to work one time, although learning how to make it do multiple times is always welcome. 例如,数组位置3需要变成数组位置1。它只需要工作一次,尽管总是欢迎学习如何使其多次执行。 It has to be done with a for loop. 它必须通过for循环来完成。 If modulo is a solution, please explain it to me since I am not entirely sure how it works. 如果取模是一种解决方案,请问给我解释一下,因为我不太确定它是如何工作的。 Here is my code: 这是我的代码:

<body>
<button type='button' onclick="Husselaar()">Husselen!</button>
        <br>
        <script>
            var games = ["Minecraft", "Assassin&#39;s Creed", "Rise Of The Tomb Raider", "Far Cry", "Tom Clancy&#39;s Rainbow Six Siege", "Call of Duty", "Grand Theft Auto V", "Hotline Miami", "American Truck Simulator", "Life is Strange"];
            var arrayLength = games.length;
            for (var i = 0; i < arrayLength; i++) {
                document.write(games[i] + "<br>");
                }
            function Husselaar(){
                    var husselaar = document.getElementById("");
                    Math.floor((Math.random(husselaar) * 9)+ 1);
                }
        </script>
</body>

Thanks in advance! 提前致谢! :) :)

You can extract a part of your array with Array.splice(startposition,amount) . 您可以使用Array.splice(startposition,amount)提取数组的一部分。

Use Array.concat to merge the old array with the resulting one. 使用Array.concat将旧数组与结果数组合并。

 var games = ["Minecraft", "Assassin&#39;s Creed", "Rise Of The Tomb Raider", "Far Cry", "Tom Clancy&#39;s Rainbow Six Siege", "Call of Duty", "Grand Theft Auto V", "Hotline Miami", "American Truck Simulator", "Life is Strange"]; function toStart() { var promptStr = "Choose the game to send to start:\\n"; for (var i = 0; i < games.length; i++) { promptStr += i + ": " + games[i] + "\\n" } var index = parseInt(prompt(promptStr)); games = games.splice(index, 1).concat(games); console.log(games); } 
 <button type='button' onclick="toStart()">Husselen!</button> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM