JavaScript 函数获取多维数组,将其展平,然后 returns 数组值按选择顺序作为字符串

JavaScript function that takes a multidimensional array, flattens it, then returns array values as string in choice order

遇到某个 objective 问题,我必须创建一个函数,该函数采用多维数组,return 是一个平面数组,其中包含使用给定多维数组中的值的句子字符串值。我很难遍历数组并将值推送到新数组。我试过的所有东西 returns 都是错误位置的值,现在它只是 returns undefined。我很失落和沮丧

定义一个函数,zooInventory,接受动物事实的多维数组。 zooInventory 应该 return 一个新的平面字符串数组。新数组中的每个元素应该是关于动物园中每种动物的句子。

let myZoo = [
  ['King Kong', ['gorilla', 42]],
  ['Nemo', ['fish', 5]],
  ['Punxsutawney Phil', ['groundhog', 11]]
];

function zooInventory(zooList) {
  let zooFlat = [];
  let name = [];
  let animal = [];
  let age = [];
  for (let i = 0; i < zooList.length; i++) {
    if (!Array.isArray(zooList[i])) {
      name.push(zooList[i])
    } else {
      animal.push(zooList[i][0]);
      age.push(zooList[i][-1]);
    }
  }
  for (let j = 0; j < name.length; j++) {
    zooFlat.push(`${name[j]} the ${animal[j]} is ${age[j]}.`)
  }
  return zooFlat;
}
zooInventory(myZoo);
/* => ['King Kong the gorilla is 42.',
       'Nemo the fish is 5.'
       'Punxsutawney Phil the groundhog is 11.']
*/

你的任务非常具体,所以我会寻求一个非常具体的解决方案:

let myZoo = [
  ['King Kong', ['gorilla', 42]],
  ['Nemo', ['fish', 5]],
  ['Punxsutawney Phil', ['groundhog', 11]]
];

function zooInventory(zooList) {
  return zooList.map(animal => animal[0] +' the '+ animal[1][0] +' is '+ animal[1][1] +'.')
}

console.log(zooInventory(myZoo))

如您所见,如果您的分配正是这样,则无需执行任何操作(例如展平),因为您只需连接从嵌套数组读取的字符串即可。

...使用的技术...

console.log([

  ['King Kong', ['gorilla', 42]],
  ['Nemo', ['fish', 5]],
  ['Punxsutawney Phil', ['groundhog', 11]]

].map(arr => {
  const [name, animal, age] = arr.flat();
  return `${ name } the ${ animal } is ${ age }`;
}));
.as-console-wrapper { min-height: 100%!important; top: 0; }

跟进

TS Playground

const myZoo = [
  ['King Kong', ['gorilla', 42]],
  ['Nemo', ['fish', 5]],
  ['Punxsutawney Phil', ['groundhog', 11]],
];

function createSentence (item) {
  const [name, animal, age] = item.flat();
  return `${name} the ${animal} is ${age}.`;
}

function zooInventory (zooList) {
  return zooList.map(createSentence);
}

console.log(zooInventory(myZoo));