Inefficient, I know, since it’s probably better to break
out of the for
loop once you find your value but just having some fun!
As we all know, you can’t search an array using the in
operator, but let’s force a square peg into a round hole. See if a value exists in an array using IN:
var test = ['one', 'two', 'three']; 'two' in (function (arr) { var o = {}; for(var x = 0; x < arr.length; x++) { o[arr[x]] = ''; } return o; } )(test); // Returns true // Make it easier on yourself var arrToObj = function (arr) { var o = {}; for(var x = 0; x < arr.length; x++) { o[arr[x]] = ''; } return o; }; // Now do it 'four' in arrToObj(test); // Returns false
The in
operator is really used to search for a property of an object, but let's see if a value exists in an object using IN:
var test = {1: 'three', 2: 'two', 3: 'one'}; var objVals = function (obj) { var o = {}; for(var p in obj) { o[obj[p]] = '' }; return o; }; 'three' in objVals(test); // Returns true 3 in objVals(test); // Returns false
Have fun coding!