首页 > 解决方案 > 将整个数组从一个函数传递到另一个函数 JavaScript

问题描述

我知道已经有很多关于这个查询的答案,但我的问题是关于接收功能。

假设我有三个功能:

function A(a){
  var j = getList(a);
  j != null? process.apply(null,j): null;
}

function getList(a){
  // returns an array like array[][] with no definite size
}

// I know this function should accept multiple arguments but I want the whole array to be passed
function process(j){
  // I want to loop the array here but it seems like
  // the argument passed is value of array[0][0]
  // 
}

我知道在c中,它应该是:

function process(j[][]){

而python直接传j也没问题。现在,javascript 让我想知道如何实现它。非常感激您的帮忙。

标签: javascript

解决方案


Apply接受参数数组,但您将单个参数作为数组传递。

有几种方法可以解决这个问题,一种方法是我只是在应用中包装j[j]这样它实际上将数组作为参数数组中的第一个元素传递。

我确信有更好的方法来解释这一点,但我想不出。

function A(a){
  var j = getList(a);
  j != null? process.apply(null,[j]): null;
}

function getList(a){
  // returns an array like array[][] with no definite size
  return a;
}

// I know this function should accept multiple arguments but I want the whole array to be passed
function process(j){
  console.log(j);
  // I want to loop the array here but it seems like
  // the argument passed is value of array[0][0]
  // 
}

A(["1","2"]);


推荐阅读