开发者

In Javascript how to compare and store the values dynamically like Key and value object

In javascript arrays i need to check and assign the values in array like key an开发者_开发问答d value pair .

For example :

if i added some values in the array and the second time the same value is retrieving one more time at that time i need to compare my array and i need to increment the previous value instead of storing the value in the array.please suggest me how to achieve this through javascript or jQuery


In sounds like you want something like a hash table. In JavaScript you should use objects for this:

var data = {};

data['key'] = 5;

// later

data['key'] += 10; // data['key'] is now 15

More information about objects in MDC - Working with Objects.

If you want to associate data with an HTML element, then have a look at jQuery's .data() [docs] method (which uses objects too, so in any case you have to learn about them ;))


If I get you right, you want to check if a given value already exists in an Array and if so, you want to increment that value by... "one" I guess ?

var foo = [10, 7, 44, 12, 102, 5],
    pos = foo.indexOf(44);

if( pos > -1 ) {
    foo[pos]++;
}


This way you can encapsulate the function which counts the numbers of occurrences of the values and the object in which the counts are stored:

var count = function() {
  var counts = {};
  return function(key) { if (typeof counts[key]=="number") counts[key]++; else counts[key]=1; return counts[key]; };
}();

document.write(count("a"));   // 1
document.write(count("b"));   // 1
document.write(count("a"));   // 2
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜