当前位置: 代码迷 >> Web前端 >> array的扩张api设计hash
  详细解决方案

array的扩张api设计hash

热度:274   发布时间:2012-09-17 12:06:51.0
array的扩展api设计hash

有的时候我们需要将两个数组合并成类似HashMap结构的对象,这个对象的组成是把第一个数组作为key,第二个数组作为value

?

说明:第一个参数是必须的,第二个参数如果未定义的话,目前可以设置为true(或者你认为的其他值)。

?

简单讲述一下思想吧:

?? ? ? ? ? ? ? ? ? ? ? ? ? ? ?1、因为返回值的是一个对象,预先定义一个返回的obj

?? ? ? ? ? ? ? ? ? ? ? ? ? ? ?2、因为是拿第一个数组的作为key,所以遍历的length按照第一个数组的length来

?? ? ? ? ? ? ? ? ? ? ? ? ? ? ?3、在遍历过程中,往预先定义的obj里面装第二个数组的值,这边就需要判断一下两个数组的长 ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?度,不够的话用true或者其他的值去代替

?

?

/*
*hash-merge the two arrays into an obj like hashMap*
*@param {Array} keys---the first array as the key*
*@param {Array} values---the second array as the value
*@remark(if values.length <keys.length will set true)*
*@return {Object} o----the merged object {key:value}*
*@remark(use the first array as the key;if the second array is not defined,we use true)*
*/
ZYC.array.hash = function(keys,values){
       var obj = {},
             _lengthOfV = values && values.length,
             _lengthOfK = keys.length,
            i;
       for(i=0;i<_lengthOfK;i++){
            obj[keys[i]] = (_lengthOfV && _lengthOfV > i) ? values[i] : true;
        }
       return obj;
}
?

?

  相关解决方案