【问题标题】:JavaScript Object/Array newbie (using jQuery)JavaScript 对象/数组新手(使用 jQuery)
【发布时间】:2011-02-03 20:44:37
【问题描述】:

我有一个需要返回数组或对象的函数。我不确定哪个是最好的,也不知道如何构建它。这是我到目前为止所拥有的。密切关注所有大写字母中的 cmets。这个想法是遍历一组包含“数据字段”属性的 td 单元格,并使用属性的名称作为变量名和包含在 td 中的文本作为值。数组/对象的属性或值的数量是未知的。根据点击进入函数的内容,将需要 2-6 个值。

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
}

【问题讨论】:

  • 听起来你需要一个哈希映射/关联数组

标签: jquery arrays object


【解决方案1】:

我相信这样的事情会为你的目的工作。

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;
}

【讨论】:

  • 为什么用大括号 {} 而不是 [] 定义 var buildup。我认为 {} 用于对象,而 [] 用于数组。
  • Buildup 是一个对象。符号 buildup["foo"] = "Fii" 与 buildup.foo = "Fii" 相同。
  • 我不知道。我更喜欢 buildup.foo ,但我想我不能使用我的字段和值变量......是吗?
  • 数组不是名称-值对的好容器。你想支持数组吗?您希望名称-值对如何存储在数组中?
  • 我同意对象更好。我只是想这样做:buildup.field = value 不起作用
【解决方案2】:

试试这个:

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;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-18
    • 1970-01-01
    • 1970-01-01
    • 2012-07-25
    • 2022-06-28
    • 1970-01-01
    相关资源
    最近更新 更多