简体   繁体   English

将值添加到多维数组的末尾

[英]Add values to end of multidimensional array

I have an array of arrays and I want to be able to add values to the array every time a user hits the add button. 我有一个数组数组,我希望每次用户按下添加按钮时都可以向数组中添加值。

var transactions = [];
transactions[0] = []; // holds date
transactions[1] = []; // holds transaction type
transactions[2] = []; // holds amount


transactions[0][i] = $("date").value;
transactions[1][i] = $("transType").value;
transactions[2][i] = parseFloat( $("amount").value);

these are the snippets . 这些是代码片段。 . . I realize I need to work on validation (which I will do) at this point I'm more concerned with loading the arrays. 我意识到我现在需要进行验证(我将做),我更关心加载数组。 The problem is the method I'm familiar with works with 1-dimensional arrays and I don't know how to replace it. 问题是我熟悉的用于一维数组的方法,但是我不知道如何替换它。

in short is it possible to reproduce this: 简而言之,可以重现此内容:

transactions[transactions.length] = $("date").value;

for a multidimensional array. 用于多维数组。

Thank You 谢谢

使用push

transactions[0].push( $("date").value );

You're looking for the Array.push() method. 您正在寻找Array.push()方法。 It allows you to push values on to the end of an array. 它允许您将值压入数组的末尾。

For your use case, you can do that on both levels of the array. 对于您的用例,您可以在阵列的两个级别上执行此操作。 See below: 见下文:

var transactions = [];
transactions.push([]);
transactions.push([]);

transactions[0].push( $('date').value );

There is no problem for using the same approach: 使用相同的方法没有问题:

transactions[0][transactions[0].length] = $("date").value;

or with push method: 或使用push方法:

transactions[0].push($("date").value);

... keeping in mind that you've initialized transactions[0] with empty array [] . ...请记住,您已使用空数组[]初始化了transactions[0] []

是的,只是多维的同义

transactions[0][transactions[0].length] = var1;

Seems a little weird you are doing: 您似乎有点不可思议:

[[array of transaction dates],[array of transaction types],[array of transaction amounts]]

Are you sure you don't want 确定要不要

[array of transactions, with date,type,amount properties]

?

var transactions = [];
transactions.push({'date': $("date").value, 'type': $("transType").value, 'amount': parseFloat( $("amount").value)});

var i = 0;

alert('date ' + transactions[i].date + ' type ' + transactions[i].type + ' amount ' + transactions[i].amount);

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

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