简体   繁体   English

在JavaScript中将元素添加到二维数组的数组中

[英]Add element inside a 2-D array's arrays in Javascript

I had a question I just couldn't find the answer to. 我有一个问题,我找不到答案。 Say I have something like the following: 说我有以下内容:

var test = [{"a": "1", "b": "2", "c": "3", "d": "4"}];

Now, say I wanted this test array to have an additional value based on some predetermined condition. 现在,假设我想这个测试阵列有基于某些预定条件的附加价值。 I could do this: 我可以这样做:

if(cond) {
    var test = [{..., "cond": true}];
}
else {
    var test = [{...}];
}

In essence, I want the array key to exist if the condition holds. 本质上,如果条件成立,我希望数组键存在。

I tried the following so far: 到目前为止,我尝试了以下方法:

test[0]["cond"] = true; // (similar to how php does it, I thought)
test[0].push("cond":true");

But they did not quite work as I intended (or at all). 但是他们并没有按照我的预期(或根本没有)工作。 How would I achieve the above? 我将如何实现以上目标? It would avoid a lot of code duplication. 这样可以避免很多代码重复。

test[0]["cond"] = true;

Should actually work as well as 实际上应该以及

test[0].cond = true;

Take into consideration that it is not actually a 2D Array, it's an Array of javascript Objects that have different methods than arrays. 考虑到它实际上不是2D数组,它是具有与数组不同方法的javascript对象数组。 For instance, javascript Object does not have a push() method. 例如,javascript对象没有push()方法。

A Object is not an Array . Object不是Array You have a Object so you can't use push . 您有一个Object因此不能使用push

You can use the first method: 您可以使用第一种方法:

 var test = [{"a": "1", "b": "2", "c": "3", "d": "4"}];

 // Here you condition
 if (cond === true) { test[0]["cond"] = true; }

See DEMO 演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM