4

I'm struggling with this. I know this is simple when you know how, but I just can't get the hang of it.

I basically want to create an object like this:

data = [{
    a: 1
    b: "test"
    c: 32
}, {
    a: 2
    b: "test2"
    c: 55
}, {
    a: 3
    b: "xyz"
    c: 103
}]

This is just an example of a larger function, so I don't want to do exactly this, but understanding tis will help me do the larger function.

I would've thought the below would work, but it doesn't quite. I'm guessing it just needs a little tweaking:

var data = new Object;

$('.class-name').each(function () {

    var a = $(this).data('a');
    var b = $(this).data('b');
    var c = $(this).data('c');

    data[] = {
        a: a,
        b: b,
        c: c
    }

});

I'm struggling with the adding to object thing and also the fact that I'm declaring the object outside the function.

I've tried data.push but I think I'm getting mixed up with arrays and objects.

Thanks for any help.

4

5 回答 5

1

为了简单起见,请这样做:

// Create an empty Array
var data = [];
$('.class-name').each(function () {

    // Get the data attribute values
    var a = $(this).data('a');
    var b = $(this).data('b');
    var c = $(this).data('c');

    // Create an empty Object
    var obj = {};

    // Set the object key-value pairs
    obj['a'] = a;
    obj['b'] = b;
    obj['c'] = c;

    // Push the object to the 'data' array
    data.push(obj);
});

// Check the data array in the console
console.log(data);

小提琴演示#1

但是您始终可以将其最小化,例如:

// Create an empty Array
var data = [];
$('.class-name').each(function () {

    // Get the data attribute values
    var a = $(this).data('a');
    var b = $(this).data('b');
    var c = $(this).data('c');

    // Push the object to the 'data' array
    data.push({a:a, b:b, c:c});
});

// Check the data array in the console
console.log(data);

小提琴演示#2

于 2013-06-26T12:42:27.617 回答
1
var data = [];

//since data is an array
//you can use it's native method `push`
//to add an object or primitive to the next/last index
data.push({
  a: 1,
  b: 'test',
  c: 32
});

您甚至可以一次将多个对象添加到数组中。

data.push({ a: 2 b: "test2" c: 55 }, { a: 3 b: "xyz" c: 103 });

或者您可以单独创建对象,然后再添加。

var someObj = {
   a: 123,
   b: 'hello',
   c: 789
};

data.push(someObj);

相关

于 2013-06-26T12:37:33.787 回答
1

您必须 d̶e̶c̶l̶a̶r̶e̶ 将data变量初始化为数组,然后“推送”新闻对象:

var data = [];

$('.class-name').each(function () {

    var a = $(this).data('a');
    var b = $(this).data('b');
    var c = $(this).data('c');

    data.push({
        a: a,
        b: b,
        c: c
    });

});
于 2013-06-26T12:38:48.333 回答
1

利用:

data = []
data.push({ a: 1, b: 'test', c: 52 })

或直接:

data = [{ a: 1, b: 'test', c: 52 }, { a: 2, b: 'test2', c: 53}]
于 2013-06-26T12:39:03.090 回答
1
data[] = …

那是 PHP 语法,而不是 JavaScript。您想改用Arraypush方法。使数据成为数组(不是通用对象):

var data = new Array;
// or simpler with an empty array literal:
var data = [];

接着

data.push({
    a: a,
    b: b,
    c: c
});
于 2013-06-26T12:49:52.437 回答