admin管理员组文章数量:1323355
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 notx
anditemNum
. For that matter you probably want to useitems.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
3 Answers
Reset to default 4var 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
版权声明:本文标题:javascript - Access an array outside of a function - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742130526a2422137.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论