簡體   English   中英

我應該如何在該多維數組中使名稱變為粗體?

[英]How should I go about making the names bold in this multidimensional array?

保持相似結構,僅在此數組中加粗名稱的最佳方法是什么? 我可以讓它在整個數組上工作(我在這里),但是我只是想獲取名稱。 我對此有一個丑陋的想法,但是希望在簡潔明了的外觀上有所幫助。 另外,我知道這不是最好的用法,我應該將數組包裝在一個對象等中,但這不是我所需要的。 這與我正在考慮的更大問題聯系在一起,並且在將來會針對更大的問題進行實踐。 謝謝。

var people = [ 
  [ "Daniel",30,"San Francisco",["175 lb"," 6\'0\""] ],
  [ "Deryl",29,"Seattle",["165 lb"," 5\'9\""] ], 
  [ "Mandie",29,"Seattle",["155 lb"," 5\'8\""] ], 
  [ "Elena",28,"Seattle",["145 lb"," 5\'6\""] ]
];

for(var i = 0; i < people.length; i++) {
    document.write("<br>"+"<b>");
    for(var j = 0; j < people.length; j++) {
        document.write(people[i][j]+"<br>");
    }
}

我已經將您的代碼組織成一個對象數組,這就是為什么。 首先,我認為它使代碼更大量可讀性。 數組數據會很快變得混亂,尤其是當您有一段時間沒有看代碼時。 以這種情況為例-您正在記錄人員姓名以及其父母的姓名。 您的數組如下所示:

['Toby', 'Chris', 'Lyndall']

從那時起,您將必須記住:

array[0] //Persons name
array[1] //Fathers name
array[2] //Mothers name

其次,這意味着您可以遍歷所有對象並輕松引用它們的任何屬性,而不必引用多維數組,這也可能會造成混淆。

 var people = [ { name: "Daniel", age: 30, location: "San Francisco", weight: "175 lb", height: "6\\'0\\"" }, { name: "Deryl", age: 29, location: "Seattle", weight: "165 lb", height: "5\\'9\\"" }, { name: "Mandie", age: 29, location: "Seattle", weight: "155 lb", height: "5\\'8\\"" }, { name: "Elena", age: 28, location: "Seattle", weight: "145 lb", height: "5\\'6\\"" } ]; people.forEach(function(person) { var html = ''; html += '<b>' + person.name + '</b>' + '<br>'; html += person.age + '<br>'; html += person.location + '<br>'; html += person.weight + '<br>'; html += person.height + '<br><br>'; document.write(html); }); 

將循環更改為此...

for(var i = 0; i < people.length; i++) {
    document.write("<br/>");
    for(var j = 0; j < people[i].length; j++) {
        var text = people[i][j];
        if (j == 0) {
            text = "<b>" + text + "</b>";
        }
        document.write(text + "<br/>");
    }
}

它的功能與以前的功能相同,但是它使用<b>標簽將每行中的第一個元素包裝起來。 有更好的方法可以做到這一點,例如使用css和類來標識列,從長遠來看,這將使維護和修改變得更加容易,但是為了學習和解決這一問題,就足夠了。

此外,有一個與內環越來越長度的問題people ,而不是具體的行。 我通過將其更改為people[i].length

people[i][0]是名稱,因此首先在<br>標記內輸出一個,然后輸出其余的?

編輯:出於可讀性考慮,也許您應該考慮將數組重構為包含JSON對象? 這樣,您就可以通過people[i].name獲得該人的名字。

您可以嘗試使用br標簽在每個people元素內包圍數組中的第一個元素。

 var people = [ [ "Daniel",30,"San Francisco",["175 lb"," 6\\'0\\""] ], [ "Deryl",29,"Seattle",["165 lb"," 5\\'9\\""] ], [ "Mandie",29,"Seattle",["155 lb"," 5\\'8\\""] ], [ "Elena",28,"Seattle",["145 lb"," 5\\'6\\""] ] ]; for(var i = 0; i < people.length; i++) { var props = people[i]; if(props.length > 0) { document.write('<b>' + props[0] + '</b>&nbsp;'); for(var j = 1; j < people[i].length; j++) { document.write(props[j]+"<br>"); } } } 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM