2011-02-03 3 views
0

私は配列またはオブジェクトを返す必要がある関数を持っています。私はどちらが最善であるかわからないし、どのように構築するのか分からない。ここに私がこれまで持っているものがあります。すべての帽子のコメントに細心の注意を払う。その考え方は、 'data-field'属性を含む一連のtdセルをループし、変数名として属性の名前を使用し、値としてtdに含まれるテキストを使用することです。配列/オブジェクトのプロパティまたは値の数は不明です。関数に入力する内容に応じて、2-6の値が必要になります。JavaScriptオブジェクト/配列newbie(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

VARの蓄積は、中括弧{}の代わりに[]で定義されている理由をハッシュマップ/連想配列 –

答えて

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

を必要とするような音。私は{}がオブジェクト用で、[]は配列用であると思った。 – Ben

+0

ビルドアップはオブジェクトです。表記ビルド["foo"] = "Fii"は、buildup.foo = "Fii"と同じです。 – JoeyRobichaud

+0

私はそれを知らなかった。私はbuilddup.fooを好むが、フィールドとバリュー変数を使うことはできないと思う。 – Ben

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; 
} 
関連する問題