gpt4 book ai didi

javascript - 在 JavaScript 中将数组元素打印到各自的列中

转载 作者:行者123 更新时间:2023-11-28 20:21:36 25 4
gpt4 key购买 nike

我需要在 JavaScript 中获取一个数组并将其以类似表格的格式打印到屏幕上。我可以毫无问题地打印列标题,但我正在努力解决的是如何以类似表格的方式在这些列下打印数据......

JavaScript 文件(数据文件):

var FirstNames = new Array();
var LastNames = new Array();

FirstNames[0] = 'First1';
FirstNames[1] = 'First2';
FirstNames[2] = 'First3';
FirstNames[3] = 'First4';

LastNames[0] = 'Last1';
LastNames[1] = 'Last2';
LastNames[2] = 'Last3';
LastNames[3] = 'Last4';

var PersonalInformation = {

FirstName : FirstNames,
LastName : LastNames

};

HTML 文件:

<!DOCTYPE html />
<html>
<title>The Data Structure</title>
<body>

<script type="text/javascript" src="TheData.js"></script>
<script>
function printObj(theObject){
var theOutputTable = '';
var theOutputHeader = '';

//Print the Column Headers for the table.
for (var theColumnHeaders in theObject){
var CreatetheTagTR = document.createElement('th');
var theColumnText = document.createTextNode(theColumnHeaders);
CreatetheTagTR.appendChild(theColumnText);
document.body.appendChild(CreatetheTagTR);
}

//Eventually, print data in the repsective columns by row.
for (var property in theObject){
theOutput = theObject[property];
var theElement = document.createElement('tr');
var theText = document.createTextNode(theOutput);
theElement.appendChild(theText);
document.body.appendChild(theElement);
}
}
printObj(PersonalInformation);
</script>
</body>
</html>

最佳答案

如果您重新排列数据,使其看起来像这样,您将可以更轻松地打印值表...

在 JavaScript 中:

//structure the array this way
var names = [
{ first: 'john', last: 'smith' },
{ first: 'frank', last: 'ricard' }
{ first: 'jimi', last: 'hendrix' }
];


//Then, you can simply iterate through the array and build a table.
for(var i = 0; names.length; i++) {
var name = names[i];
var first = name.first
var last = name.last

//build your table markup in here.
}

或者在 PHP 中:

//structure array this way
$names = array(
array('first' => 'john', 'last'=>'smith'),
array('first' => 'frank', 'last'=>'ricard'),
array('first' => 'jimi', 'last'=>'hendrix')
);

//iterate through array this way
foreach($names as $name) {
$first = $name['first'];
$last = $name['last'];
//build your table markup in here.
}

关于javascript - 在 JavaScript 中将数组元素打印到各自的列中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18198326/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com