如何逐步切分数组

问题描述 投票:0回答:2

我有一个字符串数组

const animals = ['ant', 'bison', 'camel', 'duck', 'elephant'];

对于第一个切片,我想输出'ant“

console.log(animals.slice(0, 1));

对于第二个片段,我想输出'野牛'

console.log(animals.slice(1, 2));

对于第三片,我想输出'camel'

console.log(animals.slice(2, 3));

我想继续以这种方式切成数组的长度,以输出最后一个字符串'elephant'。

对于给定的字符串数组,是否有一种方法可以使用slice()方法中的变量来自动执行此过程?

javascript arrays slice
2个回答
0
投票

使用for...of迭代器

const animals = ['ant', 'bison', 'camel', 'duck', 'elephant']

for( let i of animals )
  console.log(  i  )

带有数组forEach

const animals = ['ant', 'bison', 'camel', 'duck', 'elephant']
animals.forEach(animal => console.log(animal))

您是否有理由在问题描述中坚持使用slice


0
投票

您可以为每个循环使用a:

const animals = ['ant', 'bison', 'camel', 'duck', 'elephant'];

animals.forEach(animal => console.log(animal));
© www.soinside.com 2019 - 2024. All rights reserved.