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
Nikhil Aggarwal
28.5k4 gold badges46 silver badges61 bronze badges
asked Jun 24, 2016 at 14:55
Santiago Pérez García
212 bronze badges
1 Answer 1
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++)
Nikhil Aggarwal
28.5k4 gold badges46 silver badges61 bronze badges
answered Jun 24, 2016 at 14:57
DAXaholic
36k6 gold badges84 silver badges77 bronze badges
Sign up to request clarification or add additional context in comments.
1 Comment
DAXaholic
Glad to hear that - please accept it as answer if it solved the issue for you.
lang-js