Strong Like Bull
Strong Like Bull

Reputation: 11317

Why am I getting a javascript error in the following 3 lines of code?

var pagebacklinks = new Array();    
pagebacklinks[jQuery('#somevalue').val()]["something"] = 33; 

ERROR I GET ABOVE IS:

pagebacklinks[jQuery("#somevalue").val()] is undefined
//alert(jQuery('#somevalue').val());  This however shows the correct value

Upvotes: 0

Views: 71

Answers (5)

Netsi1964
Netsi1964

Reputation: 3620

This is how I would do it:

var pagebacklinks = []; // [] is a shorter version than new Array()

var vKeyLevelOne = jQuery('#somevalue').val(); // May be an int, or a string - a "variant"

if (typeof pagebacklinks[vKeyLevelOne]=='undefined') pagebacklinks[vKeyLevelOne] = [];

pagebacklinks[vKeyLevelOne]["something"] = 33;

Upvotes: 1

S L
S L

Reputation: 14328

It's because pagebacklinks[jQuery('#somevalue').val()] is not an array.

This should work

var pagebacklinks = new Array();    
pagebacklinks[1] = new Array();

pagebacklinks[1][2] = 'sadfasdf';

console.log(pagebacklinks[1][2]);

So the correct way should be

pagebacklinks[jQuery("#somevalue").val()] = new Array();

pagebacklinks[jQuery('#somevalue').val()]["something"] = 33; 

Upvotes: 4

alex
alex

Reputation: 490577

JavaScript doesn't have associative arrays. You can use an object here.

var pagebacklinks = [],
    index = jQuery('#somevalue').val();

pagebacklinks[index] = {'something': 33};

Upvotes: 1

xkeshav
xkeshav

Reputation: 54070

try

var $val=jQuery('#somevalue').val();

var pagebacklinks = new Array();

pagebacklinks[$val]["something"] = 33;

Upvotes: 0

Chris
Chris

Reputation: 8442

Try puting jQuery('#somevalue').val() into a variable first then use the variable in the array.

Upvotes: 1

Related Questions