admin管理员组

文章数量:1323707

I have a shopping cart, within the cart I want to store 4 items for each item

[0] DB id
[1] description
[2] cost
[3] item id

So I have whipped up a 2d array

var x=0;
var items= new Array();
var itemNum = 0

Function add(id, desc, cost )
{
items[x]=new Array(4);
items[x][0]=item;
items[x][1]=desc;
items[x][2]=cost;
items[x][3]=itemNum;
x++
itemNum++
}

How do access the array outside the function?

I have a shopping cart, within the cart I want to store 4 items for each item

[0] DB id
[1] description
[2] cost
[3] item id

So I have whipped up a 2d array

var x=0;
var items= new Array();
var itemNum = 0

Function add(id, desc, cost )
{
items[x]=new Array(4);
items[x][0]=item;
items[x][1]=desc;
items[x][2]=cost;
items[x][3]=itemNum;
x++
itemNum++
}

How do access the array outside the function?

Share Improve this question asked Oct 26, 2011 at 7:55 maxummaxum 2,9154 gold badges36 silver badges49 bronze badges 4
  • Are you getting any errors? How are you trying to access the array? – Simon Commented Oct 26, 2011 at 7:59
  • You have defined the items array outside te function and are adding items to in within the function, so what you are asking is what you are doing at the moment, don't see the problem? – Bas Slagter Commented Oct 26, 2011 at 7:59
  • 1 You probably want to be using items.length and not x and itemNum. For that matter you probably want to use items.push() and not calculate the next item and insert something into it manually. – Quentin Commented Oct 26, 2011 at 7:59
  • Fyi, you can simplyfy the code even more: items.push([item, desc, cost, itemNum]); – ThiefMaster Commented Oct 26, 2011 at 8:02
Add a ment  | 

3 Answers 3

Reset to default 4
var items = [];

function add(id, desc, cost) {
    items.push({ id : id, desc : desc, cost : cost });
}

add(1, 'test', 12345);

alert(items[0].desc);

The array is stored in the variable items, so access that as normal.

items[0]

Since items is declared outside of the function, you can access it outside of the function in the normal way:

console.log(items[0][0]); //Will print whatever is at 0,0 in the array

本文标签: javascriptAccess an array outside of a functionStack Overflow