首页 > 解决方案 > 如何在javascript中循环遍历数组以获取长度不大于4的新数组?

问题描述

我有这个数组,它的长度可以是任意数字但不小于 4。如何循环遍历这个数组以获得长度不大于 4 的新数组?我尝试使用 filter 方法,但它返回了一个空数组。

这是我的尝试:

// array could be of any length but not less than 4.
const projects = [
  'landing page',
  'portfolio page',
  'e-commerce app',
  'Dapps',
  'signup page',
  // ... even more
];

const newProjects = projects.filter((project, index, array) => {
  return project[index <= 4]
})

console.log(newProjects);

标签: javascriptarraysreactjsloopsfilter

解决方案


更正了您的方法;

const projects = ['landing page', 'portfolio page', 'e-commerce app', 'Dapps', 'signup page',.....] // array could be of any length but not less than 4

const newProjects = projects.filter((project, index, array) => {
  return index < 4;
})

console.log(newProjects);

请记住,Array 具有从零开始的索引。

建议的解决方案:

const newProjects = projects.slice(0,3);

推荐阅读