用于返回数组中长度超过定义数字的字符串的Javascript函数

时间:2015-01-15 16:34:41

标签: javascript arrays function

我正在尝试编写一个函数,该函数接受一个字符串数组和一个数字,该数字返回一个长度超过定义数字的数组中的字符串。

以下是我开始使用的代码:

var words = ["Harold", "hen", "asdasda"];

var i = 5
words.sort(function filterLongWords(x , i){
    if (words[x].length > i){
        return words[x];
    }
    else {
        console.log("You have no words longer than the number " + i + ".");
    }
}); 

谢谢!

1 个答案:

答案 0 :(得分:1)

您可以使用Array.filterArray.length

执行您打算执行的操作
var longWords = words.filter(function(str) { return str.length > i; });
if (longWords.length == 0) {
  console.log("You have no words longer than the number " + i + ".");
}