/    Sign up×
Community /Pin to ProfileBookmark

Test for array element defined …

Is there a way to tell if an array element does or does not have a value associated with it?

In PERL I would be able to:
if (!defined($arr[p])) { $arr[p] = 0; }

Is there a similar assignment with JS? ?

to post a comment
JavaScript

5 Comments(s)

Copy linkTweet thisAlerts:
@Wisest_GuyFeb 15.2008 — [CODE]if (typeof arr[index] == "undefined"){arr[index] = 0;}[/CODE]
Copy linkTweet thisAlerts:
@mrhooFeb 15.2008 — if(arr[i]===undefined) arr[i]=0;
Copy linkTweet thisAlerts:
@JMRKERauthorFeb 15.2008 — Thanks to you both.

I'll give them a try.
Copy linkTweet thisAlerts:
@toicontienFeb 15.2008 — Using the typeof function has one small annoyance. Internet Explorer 5 doesn't return "undefined" for undefined variables. If IE5 is not a concern, then use the typeof method.
Copy linkTweet thisAlerts:
@JMRKERauthorFeb 15.2008 — 'toicontien':

Thanks for the 'heads-up".

I use FF mostly, but I know my students use anything they can get their hands on.

Saves me a lot of head scratching when things don't go as expected.
×

Success!

Help @JMRKER spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 4.29,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,

tipper: @Samric24,
tipped: article
amount: 1000 SATS,
)...