Jump to content

JS Basic Question


Drongo_III
Go to solution Solved by Jacques1,

Recommended Posts

I have a really basic question.

 

Why is it you can't create a multidimensional array like this in javascript:

t['key1']['key2'] = 123;

I have worked with JS for a long time and I get the proper form is to do something like:

t['key1'] = {'key2' : 123}

 But I'm just wondering why it's not possible to do the first version?  Is it because JS doesn't know what to cast the 'key2' to?

 

Thanks,

 

Drongo

Link to comment
Share on other sites

  • Solution

This array feature which you appearently know from PHP is actually very exotic and really only makes sense in the super-sloppy PHP philosophy.

 

Technically speaking, you simply cannot apply the index operator to the empty value t['key1']. There's no such thing as null['key2']. If you try this in Ruby, your script will blow up with an error message. The same is true for Python. The only reason why PHP doesn't blow up is because it's specifically designed to accept errors. Instead of telling you to fix your code, it will guess what you mean and create a new subarray for you.

 

So this isn't how languages normally works. It's a PHPism.

Link to comment
Share on other sites

This array feature which you appearently know from PHP is actually very exotic and really only makes sense in the super-sloppy PHP philosophy.

 

Technically speaking, you simply cannot apply the index operator to the empty value t['key1']. There's no such thing as null['key2']. If you try this in Ruby, your script will blow up with an error message. The same is true for Python. The only reason why PHP doesn't blow up is because it's specifically designed to accept errors. Instead of telling you to fix your code, it will guess what you mean and create a new subarray for you.

 

So this isn't how languages normally works. It's a PHPism.

 

Thanks Jacques. You're quite right, I'm a php developer first and didn't realise this was a feature particular to php. Makes much more sense now.

 

Drongo

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.