Skip to content

Instantly share code, notes, and snippets.

@chrisjhoughton
Last active December 17, 2015 04:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chrisjhoughton/5554466 to your computer and use it in GitHub Desktop.
Save chrisjhoughton/5554466 to your computer and use it in GitHub Desktop.
See if an array/string contains something. Nothing fancy, but without a library you'll need this as array.indexOf doesn't work in IE8 and lower.
var contains = function (list, value) {
if (list instanceof Array) {
var i = list.length;
while (i--) {
if (list[i] === value) {
return true;
}
}
return false;
} else if (typeof list === "string") {
return (list.indexOf(value) !== -1);
}
};
<html>
<head>
<title>Contains tests</title>
<link rel="stylesheet" type="text/css" href="http://code.jquery.com/qunit/qunit-1.11.0.css">
<script type="text/javascript" src="http://code.jquery.com/qunit/qunit-1.11.0.js"></script>
<script type="text/javascript" src="./contains.js"></script>
<script type="text/javascript">
test("contains - arrays", function() {
strictEqual(contains([1,2,3,4], 1), true);
strictEqual(contains(["chris", "nicolas", "alex"], "chris"), true);
strictEqual(contains([1,2,3,4], 5), false)
});
test("contains - strings", function() {
strictEqual(contains("chris", "chr"), true);
strictEqual(contains("chris", "christof"), false);
});
</script>
</head>
<body>
<div id="qunit"></div>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment