【问题标题】:How to incrementally slice through an array如何增量切片数组
【发布时间】:2020-04-26 15:12:50
【问题描述】:

我有一个字符串数组

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

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

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

对于第二个切片,我想输出“bison”

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

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

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

我想继续以这种方式切分到数组的长度以输出最后一个字符串“大象”。

对于给定的字符串数组,有没有办法使用 slice() 方法中的变量自动执行此过程?

【问题讨论】:

  • 您需要使用(简单)函数为您执行此操作。另请注意,slice 将返回一个数组,因此您实际上将记录一个包含单个动物的数组

标签: javascript arrays slice


【解决方案1】:

使用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 有什么原因吗?

【讨论】:

  • 我需要对一组图像进行增量切片并在 React 中返回每个切片。我需要专门返回数值 (0,1) 、 (1,2) 、 (2,3) 等等,但我的切片现在只返回此示例中的最后一对值 (2,3) 而我需要返回每对值以将数组中的每个单独图像输出到图像库中。我只是把这个作为答案,因为它在技术上确实回答了我最初的问题,我简化了因为我的项目使用 React、Gatsby 和 GraphQL 很复杂
  • @ElijahLee - 如果我的回答没有真正帮助,您可以编辑您的问题以更好地表达您的要求
【解决方案2】:

您可以使用 for each 循环:

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

animals.forEach(animal => console.log(animal));

【讨论】:

    猜你喜欢
    • 2012-11-10
    • 2015-02-18
    • 2021-12-09
    • 2013-04-12
    • 1970-01-01
    • 1970-01-01
    • 2012-04-09
    • 2012-06-05
    相关资源
    最近更新 更多