我在JavaScript中有这个多维数组,我试图用它填充HTML头,我想填充该头,以便所有名字都分别打印在头中。有一个简单的方法可以完成此操作,因为我不确定该如何处理。任何帮助将不胜感激。
var personArr = [];
var person = {firstName:"John", lastName:"Doe", age:21};
var person2 = {firstName:"Paul", lastName:"Logan", age:22};
var person3 = {firstName:"Sean", lastName:"Kim", age:32};
var person4 = {firstName:"Ken", lastName:"Chow", age:12};
personArr.push(person, person2, person3, person4);
console.log(personArr);
<!DOCTYPE html>
<html>
<body>
<h6></h6>
<h6></h6>
<h6></h6>
<h6></h6>
</body>
</html>
答案 0 :(得分:0)
纯JavaScript实现
我们可以遍历personArr数组以获得firstName,然后将firstName存储在h6标签中
import akka.actor._
import akka.http.scaladsl._
import akka.http.scaladsl.model.ws.{Message, TextMessage}
import akka.http.scaladsl.server.Directives._
import akka.stream._
import akka.stream.scaladsl._
import scala.io.StdIn
object Server2 {
def main(args: Array[String]): Unit = {
implicit val system = ActorSystem()
implicit val materializer = ActorMaterializer()
def echoFlow: Flow[Message, Message, Any] =
Flow[Message].map {
case tm: TextMessage.Strict => TextMessage.Strict("Test " + tm.text)
case _ => TextMessage("Message type unsupported")
}
val websocketRoute =
path("chat") {
handleWebSocketMessages(echoFlow)
}
val bindingFuture = Http().bindAndHandle(websocketRoute, "127.0.0.1", 8080)
// the rest of the sample code will go here
println("- Started server at 127.0.0.1:8080, press enter to kill server")
StdIn.readLine()
system.terminate()
}
}
var personArr = [];
var person = {firstName:"John", lastName:"Doe", age:21};
var person2 = {firstName:"Paul", lastName:"Logan", age:22};
var person3 = {firstName:"Sean", lastName:"Kim", age:32};
var person4 = {firstName:"Ken", lastName:"Chow", age:12};
personArr.push(person, person2, person3, person4);
var content = "";
for(var i=0;i<personArr.length;i++)
{
content +="<h6>"+personArr[i].firstName+"</h6>";
}
document.getElementById('content').innerHTML = content ;
答案 1 :(得分:0)
将Jquery添加到文件中,并使用forEach遍历每个数组元素。然后,您可以为每个单独的对象键添加.text元素
<html>
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.3.1.min.js"></script>
<script type="text/javascript">
var personArr = [];
var person = {firstName:"John", lastName:"Doe", age:21};
var person2 = {firstName:"Paul", lastName:"Logan", age:22};
var person3 = {firstName:"Sean", lastName:"Kim", age:32};
var person4 = {firstName:"Ken", lastName:"Chow", age:12};
personArr.push(person, person2, person3, person4);
console.log(personArr);
$(document).ready(() => {
var p = 1;
personArr.forEach(function(element) {
$("#"+p).text(element.firstName);
p+=1;
});
})
</script>
<body>
<h6 id="1"></h6>
<h6 id="2"></h6>
<h6 id="3"></h6>
<h6 id="4"></h6>
</body>
</html>
您可以这样做!