javascript 如何将特定数量的空数组添加到一个空数组中?[已关闭]

55ooxyrt  于 2022-12-25  发布在  Java
关注(0)|答案(3)|浏览(192)

1小时前关闭。
Improve this question
我正在尝试创建一个递归的buildList()函数,它接受任意值并将其多次添加到一个空数组中(length参数),目前为止我所拥有的代码(使用array.concat(value))可以添加任何东西,除了空数组(它甚至可以添加空对象)。

var buildList = function(value, length, i = 1, array = []) {
  if (i > length) {
    return array;
  } else {
    return buildList(value, length, i + 1, array.concat(value));
  }
};

console.log(buildList([], 4));
//output = [], when I want it to be [[],[],[],[]]
cs7cruho

cs7cruho1#

你可以使用Array.from来代替,注意,除非你希望得到的数组多次保存相同的引用,否则你需要提供一个回调函数来返回非原语的值。

const buildList = (value, length) => Array.from({length}, 
  _ => typeof value === 'function' ? value() : value);
console.log(buildList(() => [],4));
console.log(buildList("test", 3));
vwkv1x7d

vwkv1x7d2#

问题是当你用两个数组运行array.concat()时,数组不会被推到另一个的末尾,但是它的内容会被加在一起。

var buildList = function(value, length, i = 1, array = []) {
  if (i > length) {
    return array;
  } else {
    array.push(value);
    return buildList(value, length, i + 1, array);
  }
};

console.log(buildList([], 4));
//output = [], when I want it to be [[],[],[],[]]

注意,你的代码不会对传递的对象进行深层复制,这意味着如果你改变了其中一个元素,那么所有的元素也会随之改变,如果你不想发生这种情况,那么你可以使用下面的代码:

var buildList = function(value, length, i = 1, array = []) {
  if (i > length) {
    return array;
  } else {
    array.push(structuredClone(value));
    return buildList(value, length, i + 1, array);
  }
};

console.log(buildList([], 4));
//output = [], when I want it to be [[],[],[],[]]
n7taea2i

n7taea2i3#

JavaScript很草率,允许你“连接”一个数组和一个单一的值-

const a = [1,2,3]
const b = 4
console.log(a.concat(b))
// [1,2,3,4]

但是,a.concat(b)更适合组合两个数组-

const a = [1,2,3]
const b = [4,5,6]
console.log(a.concat(b))
// [1,2,3,4,5,6]

您需要的是将嵌套的[]连接到数组。您可以使用array.concat([value])-

var buildList = function(value, length, i = 1, array = []) {
  if (i > length) {
    return array;
  } else {
    return buildList(value, length, i + 1, array.concat([value])); // concat nested
  }
};

console.log(JSON.stringify(buildList([], 4)));
// [[],[],[],[]]

或者您可以使用扩展语法[...array, []]-append

var buildList = function(value, length, i = 1, array = []) {
  if (i > length) {
    return array;
  } else {
    return buildList(value, length, i + 1, [...array, value]); // append
  }
};

console.log(JSON.stringify(buildList([], 4)));
// [[],[],[],[]]

相关问题