Javascript - 向现有数组添加新标签和数据

Javascript - Adding new label and data to existing array

本文关键字:标签 数据 新标签 添加 数组 Javascript      更新时间:2023-09-26

据我所知,可以将更多数据推送到数组中。Fe,我有一个数组:

G = [12, 34, 5]. 

现在,我可以像这样访问第 n 个元素:

G[n]

我现在想用标签在其中推送新数据,所以我希望数组看起来像

G = [12, 34, 5, label:567856, other: Infinity]

我可以在哪里通过电话获得567856

G["label"] //(or Infinity by calling G["other"]). How can I achieve this? 

我发现

G[i].push({
    label:567856, 
    other: Infinity
})

但通过这种方式,它将其添加为一个全新的元素,我只能调用 G[4]["其他"],而不是 G["其他"]。如何添加我所描述的元素?

谢谢!

要补充Andriy的答案,你需要使用Javascript对象而不是数组。对象可以具有具有自定义名称的索引。例如,给定

var newObj = {"hello": "world", "value":1, "inf": Infinity}

你可以做

newObj['hello'] // "world"
newObj['value'] // 1

问题所在

G[i].push({
    label:567856, 
    other: Infinity
})

就是你推送一个有 2 个属性的对象,而不是推送 2 个对象,这就是为什么你需要使用 G[4]["other"]

请参阅运行 JSFiddle 示例。

G["other"] = "something";

有了这个,您将保留原始数组,现在具有属性 other ,但它不在[12, 34, 5]

打这个,你可以将一个对象添加到数组中:

G.push({other: 123})
console.log(G);//[12, 34, 5, object]
console.log(G[3].other);//123

问题所在

G[i].push({
    label:567856, 
    other: Infinity
})

就是你推送一个有 2 个属性的对象,而不是推送 2 个对象,这就是为什么你需要使用 G[4]["其他"]

JavaScript 中的数组是一种对象。 因此,它们可以包含以下属性:

G.label = 567856;
G.other = Infinity;

与其他对象相比,数组的优势在于它们的索引元素是有序的

如果您希望数组中的第四和第五个元素567856Infinity,并且希望能够使用 G.labelG.other 引用这些值,则可以执行以下操作:

var G = [12, 34, 5];
G.push(G.label = 567856);     //same as G.label = 567856;  G.push(G.label);
G.push(G.other = Infinity);

您仍然可以使用循环遍历数组:

var G = [12, 34, 5];
G.push(G.label = 567856);    
G.push(G.other = Infinity);
G.forEach(function(val) {
  console.log(val);  // 12 ... 34 ... 5 ... 567856 ... Infinity
});
console.log(G.label);  //567856
console.log(G.other);  //Infinity

请注意,这确实会创建重复项。 如果之后更改G.labelG.other,这些更改将不会反映在数组的第四个和第五个元素中。

但是,您可以通过使用 Object.defineProperty()G.labelG.other上创建资源库来克服这个问题:

var G = [12, 34, 5];
G.push(G.label = 567856);
G.push(G.other = Infinity);
G.forEach(function(val) {
  console.log(val); // 12 ... 34 ... 5 ... 567856 ... Infinity
});
console.log(G.label); //567856
console.log(G.other); //Infinity
Object.defineProperty(G, 'label', {
  set: function(x) {
    this[3] = x;
  }
});
Object.defineProperty(G, 'other', {
  set: function(x) {
    this[4] = x;
  }
})
G.label = 99999;
G.other = 11111;
G.forEach(function(val) {
  console.log(val); // 12 ... 34 ... 5 ... 99999 ... 11111
});

数组

不是为适合您的情况而设计的。

参见 数组元素从 ECMAScript 262, 5.1 15.4 访问流

数组对象对特定类别的属性给予特殊处理 名字。属性名称 P(字符串值的形式)是一个数组 索引当且仅当 ToString(ToUint32(P)) 等于 P 且 ToUint32(P) 不等于 2^32−1。

因此,您根本无法按字母顺序名称访问 Array 元素,因为该键不会被 ToUint32 解析为整数。

您可以将对象添加到数组中,并在推送到数组后存储其索引(Array.prototype.push 会返回数组的大小):

var G = [1,3,4];
var labelIndex = G.push({'label': 123}) - 1;
console.log(G[labelIndex]["label"]);

实际上,当您的数组中有两个或多个具有相同属性的对象时,该解决方案将适合这种情况。

不推荐以下建议!

但是,您可以使用下面的代码来定义G Array 属性,但它不是数组中项的属性值,而是数组属性:

G.other = Infinity;
G.label = 567856;
// Access newly created properties
console.log(G["other"]);
console.log(G["label"]);

祝你好运!