简体   繁体   中英

Push an array into an array Javascript

I'm new in JavaScript and I want to transform this array ["Banana", "Orange", "Apple", "Mango"] , in this one [["Banana"], ["Orange"], ["Apple"], ["Mango"]] , but when I try to do it, my browser freezes. I'm using this code:

<script>
var i = 0;
var fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo").innerHTML = fruits;

function myFunction() {
    var fruits_aux = [];
    for (i=0; fruits.length; i++)
      fruits_aux.push([fruits[i]]);
    fruits = fruits_aux;
    document.getElementById("demo").innerHTML = fruits;
}
</script>

Be careful executing this code. Anyone can help me? Thanks

In your for loop, the condition always evaluates to true , hence, it becomes an infinite loop and the reason for your browser freeze.

for (i=0; fruits.length; i++)

should probably be

for (i=0; i < fruits.length; i++)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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