简体   繁体   中英

I can't display my sorted array with Javascript in HTML (innerHTML)

I sorted an array of integers and I tried to display it with HTML but I don't know how to do it.

I already tried to print the elements without using the function display

 var array = [4, 2, 8, 3, 5]; for (var i = 0; i < array.length; i++) { for (var j = i + 1; j < array.length; j++) { if (array[i] > array[j]) { var temp = array[i]; array[i] = array[j]; array[j] = temp; } } } function display(array) { for (var i = 0; i < array.length; i++) { console.log(array[i]); document.getElementById("visualization").innerHTML = array; } } window.document.getElementById("visualization").innerHTML = display(array); 
 <p id="visualization"></p> 

Expected result: 2,3,4,5,8 Actual result: undefined

When I use Chrome console it just works fine! There's nothing wrong about the sorting code.

Your issue here is that execution of display function returns nothing, so it implicitly returns undefined and you are setting this result ( undefined ) into innerHTML of that element. One of the possible solutions would be returning string from display function, or prepare string of all values inside that function, set innerHTML to that string, return nothing and then only call display function (below is an example)

You need to create string for innerHTML

 var array = [4, 2, 8, 3, 5]; array.sort((a,b) => a < b ? -1 : (a == b ? 0 : 1)); function display(array){ var html = ""; for(var i=0; i<array.length; i++){ console.log(array[i]); html += `<p>${array[i]} </p>`; } document.getElementById("visualization").innerHTML = html; } display(array) 
 <html> <head> </head> <body> <p id="visualization"></p> </body> </html> 

I simplified your code a bit,

Take a look at the jsFiddle,

you could just use the array sort method,

You are trying to innerHTML a function that has no return value. Instead try returning a string, Or use string join method

  var array = [4, 2, 8, 3, 5]; array.sort() document.getElementById("visualization").innerHTML = array.join(",") 
 <html> <head> </head> <body> <p id="visualization"></p> </body> </html> 

https://jsfiddle.net/mje21Lwv/

  var array = [4, 2, 8, 3, 5];

  array.sort()

  document.getElementById("visualization").innerHTML = array.join(",")

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