有区别:

 var samples = {
        "TB10152254-001": {
            folderno: "TB10152254",
            ordno: "001",
            startfootage: "",
            endfootage: "",
            tagout: "Y"
        },
        "TB10152254-002": {
            folderno: "TB10152254",
            ordno: "002",
            startfootage: "",
            endfootage: "",
            tagout: "Y"
        },

        "TB10152254-003": {
            folderno: "TB10152254",
            ordno: "003",
            startfootage: "",
            endfootage: "",
            tagout: "Y"
        }
    };

 var samples = new Array();
samples["TB10152254-001"]  = {
            folderno: "TB10152254",
            ordno: "001",
            startfootage: "",
            endfootage: "",
            tagout: "Y"};

samples["TB10152254-002"] = {
            folderno: "TB10152254",
            ordno: "002",
            startfootage: "",
            endfootage: "",
            tagout: "Y"
        };

samples["TB10152254-003"] =  {
            folderno: "TB10152254",
            ordno: "003",
            startfootage: "",
            endfootage: "",
            tagout: "Y"
        };

编辑:

我将重新阐述一个问题:如何动态填充哈希?我不能做诸如samples.tb10152254-003之类的事情,因为I TB10152254-003是动态的...所以,这甚至可能吗?

有帮助吗?

解决方案

两者都会起作用,因为数组是一种对象。但是,使用这种方式使用数组没有任何优势,当您使用A迭代属性时,可以轻松地给麻烦 for/in.

该对象将是用于命名属性的合适类型。仅保留您仅用于索引属性的数组。


关于您的编辑,您可以使用Square Bracket表示法以与数组相同的方式动态填充对象。

   // Create a new empty object. You an use "new Object()" if you wish
var samples = {};

  // Populate the "samples" object in the same way you would an Array.
samples["TB10152254-001"]  = {
            folderno: "TB10152254",
            ordno: "001",
            startfootage: "",
            endfootage: "",
            tagout: "Y"};

samples["TB10152254-002"] = {
            folderno: "TB10152254",
            ordno: "002",
            startfootage: "",
            endfootage: "",
            tagout: "Y"
        };

samples["TB10152254-003"] =  {
            folderno: "TB10152254",
            ordno: "003",
            startfootage: "",
            endfootage: "",
            tagout: "Y"
        };

其他提示

是的。在第二个示例中,您正在“滥用”一个事实 Array 也是一个 Object. 。不要这样做。

利用 ArrayS仅用于数值索引值和平原 Objects 对于有点的哈希表。

我建议阅读更多有关 ArraysObjects.

在JavaScript中,基本上一切都是对象。也是数组。但是 Array 对象提供了处理数值索引数据的其他方法。

您可能会看到最好的差异 samples.length 在第二个示例中。一个普通的对象没有属性 length, ,数组确实。对于数组,它告诉您数组中存储的元素数量。现在打电话 samples.length 在第二个示例中,您会得到 0 因为数组实际上没有任何元素。

可能导致更令人困惑的事实是,您有两种访问对象属性的可能性:“点表示法”, object.property 和“数组符号”, object['property']. 。但这是对象而非数组的功能。

当您生成键或将属性名称存储在变量中时,数组表示法就派上用场。

更新:

如书面,您可以使用数组符号动态创建属性,例如:

var samples = {};

for(var i = 0; i < 4; i++) {
    samples["TB10152254-" + i] = {
        folderno: "TB10152254",
        ordno: i,
        startfootage: "",
        endfootage: "",
        tagout: "Y"
    }
}

如果要访问属性,则必须使用 for...in 循环遍历钥匙:

for(var key in samples) {
    var value = samples[key];
}

但是请注意:从不使用 for...in 循环在数组上。我链接到的页面上也写了原因。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top