nixzhu
2013-10-04 21:36:58 +08:00
第五题花比较久的时间,重做了一遍,顺便抄录下来。这好像就是写C的人会写出的风格,没有花哨的东西。最后一题取巧了一点:
第一题:
function doubleInteger(i) {
    // i will be an integer. Double it and return it.
    return i+=i;
}
第二题:
function isNumberEven(i) {
    // i will be an integer. Return true if it's even, and false if it isn't.
    return i%2 == 0;
}
第三题:
function getFileExtension(i) {
    // i will be a string, but it may not have a file extension.
    // return the file extension (with no period) if it has one, otherwise false
    var l = i.split('.');
    if (l && l.length > 1) {
        return l[l.length-1];
    } else {
        return false;
    }
}
第四题:
function longestString(i) {
    // i will be an array.
    // return the longest string in the array
    var str ='';
    for (var x=0; x < i.length; x++) {
        if (typeof i[x] === 'string' && i[x].length > str.length) {
            str = i[x];
        }
    }
    return str;
}
第五题:
function arraySum(i) {
    // i will be an array, containing integers, strings and/or arrays like itself.
    // Sum all the integers you find, anywhere in the nest of arrays.
    var sum = 0;
    for (var x=0; x < i.length; x++) {
        if (!(typeof i[x] === 'string')) {
            if (i[x] instanceof Array) {
                sum += arraySum(i[x]);
            } else {
                sum += i[x];
            }
        }
    }
    return sum;
}