如何为对象添加索引和值?

时间:2014-10-28 09:30:54

标签: javascript jquery arrays object

如何向对象添加索引和值,下面是我的代码,我尝试在循环中添加索引和值,但它显示错误undefined is not an object ($data.file_list_image.i.sequence),为什么以及如何解决它?

尝试获取json数据并发送到服务器端

渴望数据

$data = {file_list_image: {0: {sequence: 1, intro: }, 1: {sequence: 1, intro: }, }}

JS

var $el = $content_list.find('.content-list-gallery-file-list');
var file_length = $el.length;
var file_image_length = 0;
var file_embed_youtube_length = 0;

for (var i = 0; i < file_length; i++) {
    if ($el.eq(i).attr('data-type') == 0) { // console.log('img');
        file_image_length++;
    } else if ($el.eq(i).attr('data-type') == 1) { // console.log('video');
        file_embed_youtube_length++;
    }
}

var $data = {};


for (var i = 0; i < file_image_length; i++) {
    var $file_list = $el.filter(function () {
        return $(this).attr('data-type') == 0 && $(this).attr('data-tmp-id') == i;
    });

    var sequence = $file_list.attr('data-sequence');
    var intro = $file_list.find('.intro textarea').val();


    $data.file_list_image.i.sequence = sequence;
    $data.file_list_image.i.intro = intro;
}

console.log($data);

HTML

<div class="content_list">
  <div class="content-list-gallery-file-list" data-type="0" data-tmp-id="1" data-sequence="0">
    <div class="intro"><textarea></textarea></div>
  </div>
  <div class="content-list-gallery-file-list" data-type="0" data-tmp-id="0" data-sequence="1">
    <div class="intro"><textarea></textarea></div>
  </div>
  <div class="content-list-gallery-file-list" data-type="1" data-tmp-id="2" data-sequence="2">
    <div class="intro"><textarea></textarea></div>
  </div>
</div>

1 个答案:

答案 0 :(得分:1)

如何通过在正确的时间初始化对象属性来完成它:

Fiddle example

var $data = {};
$data.file_list_image = {};
for (var i = 0; i < 5; i++)
{
    $data.file_list_image[i] = {};
    $data.file_list_image[i]["sequence"] = "seq" + i;
    $data.file_list_image[i]["intro"] = "in" + i;
}
console.log($data);

顺便说一下,$data.file_list_image[i]["sequence"](与intro相同)也可以是$data.file_list_image[i].sequence

Fiddle example with original HTML