在javascript中按字符串长度过滤数组 [英] Filter array by string length in javascript

查看:21
本文介绍了在javascript中按字符串长度过滤数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 JavaScript 的真正初学者

I'm a really beginner in javascript

我有一个包含

array_1 = ["the","quick","brown","fox","jumped","over","the","lazy","dog"]

我想要另一个数组,但只包含长度 > 3 的单词

And I want another array but only with words that have length > 3

array_cleaned = ["quick","brown","jumped","lazy"]

目前的实施方式:

array_1 = ["the","quick","brown","fox","jumped","over","the","lazy","dog"]

array_clean = [];
for(var i=0; i<array_1.length; i++){
    if(array_1[i].length > 3) 
        array_clean.push(array_1[i]);
}

document.write(array_clean)

但我正在寻找一种方法来实际过滤它.有什么想法吗?

But I'm looking for a way to actually filter it. Any ideas?

推荐答案

您可以使用 filter 方法:

You can use filter method:

const array_1 = ["the", "quick", "brown", "fox", "jumped", "over", "the", "lazy", "dog"];

const new_array = array_1.filter((element) => {
  return element.length > 3;
});

// OR refactor
// const new_array = array_1.filter( (element) => element.length > 3);

console.log(new_array)

// Output:
// ["quick", "brown", "jumped", "over", "lazy"]

这篇关于在javascript中按字符串长度过滤数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆