jQuery/JavaScript对象,添加到内部函数中

4

我很困扰这个问题。我知道这个问题很简单,但是我就是不会。

我想要创建像这样的一个对象:

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

这只是一个大函数的示例,所以我不想完全按照这个做,但理解它会帮助我完成更大的函数。

我本以为下面的代码可以工作,但实际上并没有。我猜测只需要稍微调整一下:

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
    }

});

我在添加对象方面遇到了困难,还有一个问题是我在函数外声明了对象。

我尝试使用data.push,但我认为我混淆了数组和对象。

感谢任何帮助。


1
你已经将data变量初始化为一个Object而不是一个array。请将data = new Object更改为data = [],看看是否有所改变。然后继续使用data.push - Kyle
5个回答

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

请参见相关链接 related

我将此标记为答案,因为这是最早的答案之一,也是我遵循以使其正常工作的答案。所有答案都很好,Palash Mondal的答案可能是最详细的。我不能接受所有答案,也不接受任何答案都没有帮助,所以我选择了这个。谢谢大家。 - user2143356

1
您需要将data变量声明为数组,并稍后使用“push”方法添加新闻对象:
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
    });

});

JS中没有类型声明。虽然你可能是想表达正确的意思,但“declare variable as”听起来不太对。 - Bergi

1

使用:

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

直接写出来:
data = [{ a: 1, b: 'test', c: 52 }, { a: 2, b: 'test2', c: 53}]

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

FIDDLE DEMO #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


1
data[] = …

这是PHP语法,不是JavaScript。 您需要使用Array push方法。将data设置为一个array(而不是通用对象):

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

然后

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接