2011-02-03 29 views
0

我有一個函數,需要返回一個數組或對象。我不確定哪個是最好的,我不知道如何構建它。這是迄今爲止我所擁有的。密切關注所有CAPS中的評論。這個想法是循環遍歷一組包含「data-field」屬性的td單元格,並將該屬性的名稱用作變量名稱,並將td中包含的文本用作值。數組/對象的屬性或值的數量未知。根據所點擊的功能,需要2-6個值。JavaScript的對象/數組新手(使用jQuery)

function InlineEditMode(rowID, entryType) { 
// store current row data in case of cancel 
var original = $('#'+rowID).contents(); 

// DEFINE SOME ARRAY OR OBJECT HERE 
// put original values in the newEntry Array with a loop, using the 
// data-field attributes as the name of the array or object variables 
// and the text of the td as the value 
$('#'+rowID+' td[data-field]').each(function() { 
    var field = $(this).attr('data-field'); 
    var value = $(this).text(); 

    // BUILD OUT OBJECT OR ARRAY 
}); 
// RETURN ARRAY OR OBJECT 
} 
+0

聽起來像是你需要一個HashMap /關聯數組 – 2011-02-03 20:52:35

回答

2

我相信像這樣的東西可以用於您的目的。

function InlineEditMode(rowID, entryType) { 
// store current row data in case of cancel 
var original = $('#'+rowID).contents(); 

// DEFINE SOME ARRAY OR OBJECT HERE 
var buildup = {}; 

// put original values in the newEntry Array with a loop, using the 
// data-field attributes as the name of the array or object variables 
// and the text of the td as the value 
$('#'+rowID+' td[data-field]').each(function() { 
    var field = $(this).attr('data-field'); 
    var value = $(this).text(); 

    // BUILD OUT OBJECT OR ARRAY 
    buildup[field] = value; 
}); 
// RETURN ARRAY OR OBJECT 

return buildup; 
} 
+0

爲什麼VAR積聚與大括號{},而不是[]定義。我認爲{}是針對對象的,而[]是針對數組的。 – Ben 2011-02-03 20:56:24

1

試試這個:

function InlineEditMode(rowID, entryType) { 
// store current row data in case of cancel 
var original = $('#'+rowID).contents(); 

var toReturn = {}; 

// DEFINE SOME ARRAY OR OBJECT HERE 
// put original values in the newEntry Array with a loop, using the 
// data-field attributes as the name of the array or object variables 
// and the text of the td as the value 
$('#'+rowID+' td[data-field]').each(function() { 
    var field = $(this).attr('data-field'); 
    var value = $(this).text(); 

    toReturn[field] = value; 
}); 
// RETURN ARRAY OR OBJECT 
return toReturn; 
}