/    Sign up×
Community /Pin to ProfileBookmark

How do I check if element of array exists?

In the following test code, is there a way to see if an element of the array already exists? I want to initialize it if it does not and append to it if it does.

[code=php]
<html>
<head>
<title>Append Elements</title>
<script type=”text/javascript”>
var Info = new Array();
var cnt = 0;
function AddInfo(str) {
// how do I check to see if element of hash needs to be created or if it already exists

// if (Info[str] == ‘undefined’) { Info.push(str); // doesn’t work well
if (Info[str] != ”) { Info.push(str); }
Info[str] += ‘:’+cnt; cnt++;
// above almost works, but get undefined errors
}
function ShowInfo() {
document.getElementById(‘entry’).value = ”;
foreach (var e in Info) {
document.getElementById(‘InfoText’).value = e+Info[e];
}
}
</script>
</head>
<body>
<input id=”entry” value=””>
<button onClick=”AddInfo(this.value)”>Add</button>
<button onClick=”ShowInfo()”>Show</button>
<br />
<textarea id=”InfoText” cols=”30″ rows=”10″></textarea>
</body>
</html>
[/code]

Is this a correct approach or should the
var Info = new Array();
instead be
var Info = new Object();

Any suggested changes welcomed! Thanks. ?

to post a comment
JavaScript

6 Comments(s)

Copy linkTweet thisAlerts:
@scragarFeb 13.2008 — make it an array, then you can use:
[code=php]Array.prototype.isKey = function(){
for(i in this){
if(i === arguments[0])
return true;
};
return false;
};

if (Info.isKey(str)){
Info[str] = "xyz";// you get the idea.
}
[/code]

if that's not what your after how about:
[code=php]Array.prototype.inArray = function(){
var i;
for(i=0; i < this.length; i++){
if(this[i] === value)
return true;
};
return false;
};[/code]
Copy linkTweet thisAlerts:
@mrhooFeb 13.2008 — Sometimes you want to know the index of an array item.

Like a string indexOf method, this method returns 0 for the first element,

and [B]-1 if the argument is not found in the array[/B].

[CODE]Array.prototype.indexAt= function(what){
var L= this.length;
var i= 0;
while(i< L){
if(this[i]=== what) return i;
++i;
}
return -1;
}
[/CODE]


You can make it even simpler to add an item to an array if it is not already included:

[CODE]Array.prototype.add= function(wot){
if(this.indexAt(wot)== -1) this.push(wot);
return this;
}[/CODE]


info.add(str)
Copy linkTweet thisAlerts:
@scragarFeb 13.2008 — 
[CODE]Array.prototype.indexAt= function(what){
var L= this.length;
var i= 0;
while(i< L){
if(this[i]=== what) return i;
++i;
}
return -1;
}[/CODE]
[/QUOTE]

rewrote to make it smaller, hope you don't mind:
[code=php]Array.prototype.indexAt = function(){
for(var i = 0; i < this.length; i++){
if(this[i]===arguments[0])
return i;
};
return -1;
};[/code]
Copy linkTweet thisAlerts:
@JMRKERauthorFeb 13.2008 — Thanks 'scragar' and 'mrhoo'

Lots of food for thought. I haven't use .prototype. before that I know of.

I'll come back after some more research of this concept as I'm a little unclear on exactly how to implement it.

I appreciate the help!
Copy linkTweet thisAlerts:
@scragarFeb 13.2008 — prototype is just a method of assigning a function to all future instances of a set type, in this case arrays.

basicly you can do this:
var x = new Array();
x.indexAt('cheese');
instead of the more long winded aproach that you would otherwise have to use:var x = new Array();
indexAt('cheese', x);// or something similar
Copy linkTweet thisAlerts:
@mrhooFeb 13.2008 — for(var i = 0; i < this.length; i++){ [/QUOTE]

Scragar, the for loop is fine, but having to evaluate the array length in each iteration is inefficient.

Better to get the length before the loop starts, as long as the loop itself does not change the length-

var L=this.length;

for(var i = 0; i < L; i++){

Reading arguments[0] in each test is also a bit more work than you need to do.

Little things add up- sometimes the shortest code is not the best solution.
×

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,
)...