最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

How to use a complex associative array in javascript? - Stack Overflow

programmeradmin1浏览0评论

I need this table .html#details in my program and I'm not even sure if an associative array is the way to go.

Given the type (numeric/alphanumeric), number of characters and EC (error correction) level, I want a function to return the version (first column).

I need this table http://code.google./apis/chart/docs/gallery/qr_codes.html#details in my program and I'm not even sure if an associative array is the way to go.

Given the type (numeric/alphanumeric), number of characters and EC (error correction) level, I want a function to return the version (first column).

Share Improve this question edited Oct 13, 2016 at 8:58 Brian Tompsett - 汤莱恩 5,89372 gold badges61 silver badges133 bronze badges asked Dec 21, 2010 at 4:13 Mr Rab LorcsMr Rab Lorcs 231 silver badge3 bronze badges 0
Add a ment  | 

1 Answer 1

Reset to default 8

First, JavaScript has "Arrays" and "Objects". By 'associative array' I assume you mean a JavaScript Object, using keys other than non-negative integers.

You can create JavaScript object literals using syntax such as the following:

var versions = {
  "1" : {
    rowcols : [21,21],
    charsByECLevel : {
      L : {
        digits:41,
        alpha:25
      },
      M : {
        digits:34,
        alpha:20
      }
    }
  },
  "2" : {
    rowcols : [25,25],
    charsByECLevel : {
      L : {
        digits:77,
        alpha:47
      },
      M : {
        digits:63,
        alpha:48
      }
    }
  }
};

You would then access the properties like so:

console.log( versions[1].charsByECLevel.L.digits );
// 41

To loop through the values, you could do this:

function findVersion( versions, level, digits ){
  for (var versionNumber in versions){
    if (versions.hasOwnProperty(versionNumber)){
      if (versions[versionNumber].charsByECLevel[level].digits == digits){
        return versionNumber;
      }
    }
  }
}

findVersion( versions, "L", 77 );
// returns "2"

Edit: Having written the above, if you only want to look up versions based on level and digits, you should probably reverse the hash. Instead of looping through and checking the versions, index them directly and look it up in constant time:

var versionByLevelAndDigits = {
  L : {
     41 : 1,
     77 : 2,
    127 : 3
  },
  M : {
     34 : 1,
     63 : 2,
    101 : 3
  }
};

var version = versionByLevelAndDigits["L"][77];
// 2
发布评论

评论列表(0)

  1. 暂无评论