1. Advertising
    y u no do it?

    Advertising (learn more)

    Advertise virtually anything here, with CPM banner ads, CPM email ads and CPC contextual links. You can target relevant areas of the site and show ads based on geographical location of the user if you wish.

    Starts at just $1 per CPM or $0.10 per CPC.

Using Numbers as a Key Value in Objects

Discussion in 'JavaScript' started by Borduhh, Jul 19, 2013.

  1. #1
    How can I make this work?

    // JavaScript Document
    var sampleArray = [1,2,3,4,5];
    var double = function(num){
        return (num * 2);
    };
    var doubledNum = new Object();
     
    for(var i = 0; i < sampleArray.length; i++){
        doubledNum.sampleArray[i] = double(sampleArray[i]);
    }
    Code (markup):

     
    Borduhh, Jul 19, 2013 IP
  2. Borduhh

    Borduhh Well-Known Member

    Messages:
    767
    Likes Received:
    31
    Best Answers:
    0
    Trophy Points:
    150
    #2
    Okay so I have found that using numbers cannot be done. So using number notation should look like:

    console.log(doubledNum.['1']);
    Code (markup):
    This should print out the number 2 correct?
     
    Borduhh, Jul 19, 2013 IP
  3. Borduhh

    Borduhh Well-Known Member

    Messages:
    767
    Likes Received:
    31
    Best Answers:
    0
    Trophy Points:
    150
    #3
    Solved:

    // JavaScript Document
    var sampleArray = [1,2,3,4,5];
    var doubledNum = new Object();
    var double = function(num){
        return (num * 2);
    };
     
    for(var i = 0; i < sampleArray.length; i++){
        doubledNum[sampleArray[i]] = double(sampleArray[i]);
    };
     
    console.log (doubledNum);
    Code (markup):
     
    Borduhh, Jul 19, 2013 IP
  4. JoeSimmons

    JoeSimmons Greenhorn

    Messages:
    11
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    21
    #4
    Nice. If your browser supports Array.forEach, you could shorten that:

    var numbers = [1, 2, 3, 4, 5];
    var doubled = {};
    
    numbers.forEach(function (val, i, arr) {
        doubled[val] = val * 2;
    });
    Code (markup):
     
    JoeSimmons, Aug 10, 2013 IP