简体   繁体   English

我无法使用HTML(innerHTML)中的Javascript显示排序后的数组

[英]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. 我对整数数组进行了排序,并尝试用HTML显示它,但我不知道该怎么做。

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 预期结果:2,3,4,5,8实际结果:未定义

When I use Chrome console it just works fine! 当我使用Chrome控制台时,一切正常! 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. 这里的问题是display函数的执行不返回任何内容,因此它隐式返回undefined并且您正在将此结果( undefined )设置到该元素的innerHTML中。 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) 一种可能的解决方案是从display函数返回字符串,或者准备该函数内部所有值的字符串,将innerHTML设置为该字符串,不返回任何内容,然后仅调用display函数(下面是一个示例)

You need to create string for innerHTML 您需要为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, 看一下jsFiddle,

you could just use the array sort method, 您可以只使用数组排序方法,

You are trying to innerHTML a function that has no return value. 您正在尝试使用innerHTML一个没有返回值的函数。 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/ https://jsfiddle.net/mje21Lwv/

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

  array.sort()

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

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

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