开发者

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

开发者 https://www.devze.com 2023-02-22 03:55 出处:网络
var pagebacklinks = new Array(); pagebacklinks[jQuery(\'#somevalue\').val()][\"something\"] = 33; ERROR I GET ABOVE IS:
var pagebacklinks = new Array();    
pagebacklinks[jQuery('#somevalue').val()]["something"] = 33; 

ERROR I GET ABOVE IS:

pagebacklinks[jQuery("#somevalue").val()] is undefined
//alert(jQuery('#s开发者_JAVA技巧omevalue').val());  This however shows the correct value


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; 


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


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

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

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


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;


try

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

var pagebacklinks = new Array();

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

精彩评论

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