Last active
December 17, 2015 04:59
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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