javascript - 如何在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);
解决方案
更正了您的方法;
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);
推荐阅读
- javascript - 全局变量和函数的javascript提升
- python - 为什么 os.path.exists() 会阻止 Windows 命名管道连接?
- cassandra - 从 Apache Cassandra 到 Ignite 的连接器
- redirect - 带有重定向的drupal 7网站垃圾邮件
- c++ - 模板类和好友模板函数
- vba - 我可以使用 VBA 在电子邮件中添加 RangetoHTML(rng) 然后 strbody 吗?
- javascript - for循环和setInterval,幻灯片放映
- c++ - 是否可以使用将模板参数作为模板参数的类型?
- python - python读取文件,打印以特定字符串开头的部分行
- ruby-on-rails - 在 rails 中下载由 XlsxWriter 创建的 XLSX 文件