Skip to main content

Posts

Showing posts from April, 2018

JavaScript and Python: Check if Property is in Object (or Dictionary)

JavaScript There are more than one method to check it. First, we can use hasOwnProperty method. let object = {"one": 2, "tree": "floor", 5: "socks"}; console.log(object.hasOwnProperty("tree")); // true console.log(object.hasOwnProperty(4)); // false // (Not in the object) We'll expect boolean output. Second, we can use in operator. let object = {"one": 2, "tree": "floor", 5: "socks"}; console.log("tree" in object); // true console.log(4 in object); // false // (Not in the object) We'll expect boolean output. Third, straight away access the property name we need to find out. let object = {"one": 2, "tree": "floor", 5: "socks"}; console.log(object.tree); // "floor" // (Value of that property) console.log(object[4]); // undefined // (Undefined value from that given property name in the object) We'll exp...

JavaScript and Python: Check if Item is in Array (or List)

JavaScript We can use indexOf method to do that. let a = ["one", 2, "tree", "floor", 5, "socks"]; console.log(a.indexOf("floor")); // 3 console.log(a.indexOf(4)); // -1 // (Not in the array) Using indexOf , we'll expect integer output. Returned value -1 (negative one) is to tell that the item isn't present in the array. In latest version of ECMA (latest browsers), we can use includes method. let a = ["one", 2, "tree", "floor", 5, "socks"]; console.log(a.includes("floor")); // true console.log(a.includes(4)); // false Using includes , we'll expect boolean output (true / false). Python Well, the phrase itself, "check if item in list", then we can use in operator to do that. list = ["one", 2, "tree", "floor", 5, "socks"] print 1 in list # False print "tree" in list # True Using that method, we'll ...