January 20 2013

Jquery Array Key Search

Tagged Under : ,

jquery
How to using jQuery search the array key or check for a key exists in an array.

Since JavaScript doesn’t really have associative arrays, then we only write a function to check.

var foo = {
	my: "60",
	sg: "80",
	us: "50",
	au: "40",
	hk: "90",
	cn: "30",
	tw: "55",
};
Use in to check for a key:
function key_exists($key, $array) {
	if ( !( $key in $array ) ) {
		return false
	}
	return true;
}
How to use:
//key_exists(key, search array)
if (key_exists('my', foo)) {
	alert('found');
} else {
	alert('no found');
}
If the key exists it will return true and popout an alert with found message.

Make a Comment

You must be logged in to post a comment.