Search code examples
actionscript-3flash

When would you use hasOwnProperty on an array?


I have just seen an example where the code is as follows:

var schemaSet:Array = currentScope();
if (schemaSet.hasOwnProperty("current"))
    schema = schemaSet["current"];

I have never seen this before. I checked the as3 docs and didn't find any information on it. Note: This code is from SchemaManager.currentSchema() written by an Adobe employee.

When and where would you use this? Is this better than or equivalent to:

if (schemaSet.indexOf("current")!=-1)

Solution

  • There are two types of data:

    • Normal arrays, which contain only values and the keys are numeric, starting from 0.

    • And there are also objects, where every element has a string (it can also be a number too) key.

    If you want to check if an array contains a value, you will go with .indexOf() method.

    var myArray = ["a", "b", "c"];
    
    if (myArray.indexOf("a") > -1) return true;
    

    If you want to check if an object has an element with a certain key, then you will go for hasOwnProperty() method.

    var myObject = {a: "letter a", b: "letter b"}
    
    if (myObject.hasOwnProperty("a")) return true;