在php中,您可以轻松打印关联数组的键值对,如下所示:
<?php
$array = [
"id" => "10",
"name" => "Hans",
"age" => 20
];
foreach($array as $key => $value) {
echo "$key \t $value \n";
}
输出:
id 10
name Hans
age 20
这如何与JavaScript一起使用?
注意:这是一个自我回答的问题(share your knowledge, Q&A-style)
答案 0 :(得分:0)
这是javascript的工作原理。
var myObject = {
name: "hans",
id: 10,
age: 20
}
var output = "";
for (var key in myObject) {
output += key + " = " + myObject[key] + "<br>";
}
document.getElementById("out").innerHTML = output;
&#13;
<p id="out"></p>
&#13;
<强>输出:强>
name = hans
id = 10
age = 20
var person1 = {firstName:"John", lastName:"Doe", age:46};
var person2 = {firstName:"Hans", lastName:"Oettinger", age:42};
var persons = new Array();
persons.push(person1);
persons.push(person2);
outputArray(persons);
function outputArray(pArray)
{
var output = "";
for(var i in pArray) {
output += "<ul>";
for (var key in pArray[i]) {
output += "<li>" + key + ": " + pArray[i][key] + "</li>";
}
output += "</ul>";
}
$("#output").html(output);
}
&#13;
li {
list-style-type: none;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="output"></p>
&#13;