如何通过其值查找哈希中的键? (JavaScript的)

时间:2014-06-27 07:01:14

标签: javascript hashtable

我下面有一个小程序,它接受一个字符串数组作为输入,比如["abc","defg","z","hijk"]。字符串被逐一取出并存储在散列中,它们各自的长度记录在它们旁边。例如---> { abc: 3, defg: 4, z: 1, hijk: 4 }

形成一个新数组,刚刚创建的所有键的值都进入其中。最大数量被删除两次。第三个Max值是我抓过的值。既然我拥有它,我该如何调用相关的密钥?

例如:如果strArr["abc","defg","z","hijk"],因为" abc"是3个字符,然后我们返回3,这是" abc"。我如何实际参考" abc"在上面的哈希中它的值是多少?

另一个说明性示例,如果strArr恰好是["hello", "world", "before", "all"],那么您的最终输出应该是与world相关联的5,因为"before"长度为6个字母,并且"hello""world"都是5,但输出应为world,因为它显示为数组中的最后5个字母单词。

 var hashObject = {};
 var strArr = ["abc","defg","z","hijk"];


function ThirdGreatest(strArr) {
    var count = 0;
    for(var i = 0; i<strArr.length; i++) {
        var cur = strArr[i];
        var curLen = cur.length;
        hashObject[cur] = curLen;

    }
    console.log(hashObject);
    var newArr = [];

    for(var x = 0, keys = Object.keys(hashObject), xx = keys.length; x < xx; x++) {
        var val = hashObject[keys[x]];
        newArr.push(val);
//here we form an array of the key values from above
    } 
    console.log(newArr);

    for(var j = 0; j < 2; j++) {
        console.log(newArr);
        newArr.splice(newArr.indexOf(Math.max.apply(Math,newArr)),1);
//here we remove the Max value two times


    }
        return Math.max.apply(Math,newArr); //This is the 3rd largest string's value.
        //But how do I use this to return the key associated with it instead, please?

 }



console.log(ThirdGreatest(strArr));

0 个答案:

没有答案