查找数组中最长的字符串(即使它是一个数组数组)

时间:2015-08-23 01:57:48

标签: javascript arrays string sorting

当我运行时:

var array= [123, ["hello", 67, 888888], "try", {key: "key", value: "this is the longest String"}]
longestString(array);

correct answer:
>>>"this is the longest String" 

current answer:
>>>"try" 

如何更新此功能以通过上述测试并返回正确答案?

下面是longestString()函数:

function longestString(array) {
    // return the longest string in the array
    var longest = 0;
    var longestString = "";
    for (var i = 0; i < array.length; i++) {
        if (array[i].length > longest && typeof array[i] =="string") {
        longest = array[i].length;
        longestString = array[i];
        }
    }
    return longestString;
}

1 个答案:

答案 0 :(得分:6)

添加typeof以检查数据是否为字符串

像这样

function longestString(array) {
    // return the longest string in the array
    var longest = 0;
    var longestString = "";
    for (var i = 0; i < array.length; i++) {
        if (array[i].length > longest && typeof array[i] ==="string") {
        longest = array[i].length;
        longestString = array[i];
        }
    }
    return longestString;
}

修改

对于嵌套数组/对象中的字符串?

试试这个

function longestString(array) {
    // return the longest string in the array
    var longest = 0;
    var longestString = "";
    for (var i = 0; i < array.length; i++) {
        if (Object.prototype.toString.call(array[i]) === '[object Array]') {
            array[i].forEach(function (it) {
                if (it.length > longest) {
                    longest = it.length;
                    longestString = it;
                }
            })
        } else if (Object.prototype.toString.call(array[i]) === '[object Object]') {
            for (var j in array[i]) {
                if (array[i][j].length > longest) {
                    longest = array[i][j].length;
                    longestString = array[i][j];
                }
            }
        } else if (typeof array[i] == "string" && array[i].length > longest) {
            longest = array[i].length;
            longestString = array[i];
        }
    }
    return longestString;
}

console.log(longestString([123, ["hello", 67, 888888], "try", {
    key: "key",
    value: "this is the longest String"
}]));