如何调用数组函数?

时间:2016-11-26 03:40:26

标签: javascript arrays

我将以下代码放在外部.js文件中,但我试图调用该函数,它返回undefined。 Plz帮助

   function getTransactions(accno) {
    var from, to, selected=new Array();
    var transactionPool=new Array();
    transactionPool[0]=new createTrans("1/20/2015", "PPS Payment", "dr", 1300.5);
    transactionPool[1]=new createTrans("2/27/2015", "Online", "cr", 300.5);
    transactionPool[2]=new createTrans("1/11/2016", "ATM", "dr", 9300.0);
    transactionPool[3]=new createTrans("2/20/2016", "Counter", "dr", 300.5);
    transactionPool[4]=new createTrans("3/15/2016", "Online", "dr", 2200);
    transactionPool[5]=new createTrans("4/23/2016", "PPS Payment", "dr", 4300.99);
    transactionPool[6]=new createTrans("5/2/2016", "Counter", "cr", 7300.5);
    transactionPool[7]=new createTrans("6/5/2016", "Online", "dr", 500.5);
    transactionPool[8]=new createTrans("7/20/2016", "ATM", "cr", 800.3);
    transactionPool[9]=new createTrans("11/5/2016", "PPS Payment", "cr", 300.5);    
    from=Math.floor(Math.random()*10);
    to=Math.floor(Math.random()*10+1);
    for (i=0; i<to; i++) {
        selected[i]=transactionPool[from];
        from=(from+1)%9;
    }
    return selected; 
}


<script>window.onload = function () { 
document.getElementById("account").
innerHTML =  localStorage.accDetails;
var accDetail=getTransactions();
document.getElementById("test").innerHTML = transactionPool[0];
}</script>

我在脚本中写这个来调用函数但不起作用。我的代码有什么问题?感谢。

2 个答案:

答案 0 :(得分:0)

嗯,首先,在你的脚本标签中没有名为transactionPool的变量,因为对返回数组的引用名为accDetail而不是transactionPool,而transactionPool(正确)不是全局变量。

答案 1 :(得分:-1)

一点建议:不要使用&#34; new Array()&#34;但要使用&#34; []&#34;声明数组!

&#13;
&#13;
var list = [
  function(){ // 0
    return 'cat';
  },
  function(){ // 1
    return true
  },
  function(){ // 2
    return false;
  },
  function(){ // 3
    return 'food';
  }
];

// RUN!!
alert( list[2]() );
&#13;
&#13;
&#13;