I'm looking for a smart way to check an object parameter passed to a function

I am in the following situation:

I need to check if the object parameter is really passed to the function:

Exmaple:

function (opt) {
     if (opt && opt.key && opt.key2) {
         // make something
     }
}

Is there a better way to do such a check?

+5
source share
6 answers

What you do is valid, but it has flaws.

if (opt && opt.key && opt.key2) {

This check will fail if it opt.keyhas false values ​​[0, null, false, etc.]

In this case, you will need to do a type check to make sure that it is not undefined.

if (opt && typeof opt.key !== "undefined" && opt.key2) {
0
source

Not really.

If you can not use opt.pleaseReadMyMind(); -)

You can create a method that will check if all fields have values ​​other than null.

+1

.

:

if( typeof opt !== "undefined" && typeof opt.key !== "undefined" && typeof opt.key2 !== "undefined") {

, , .

+1

:

// usage: testProps(object to test, [list, of, property, names])
// returns true if object contains all properties
function testProps(obj, props)
{
  if (obj === null)
    return false;

  var i;
  for (i=0; i<props.length; ++i) 
  {
    if (!(props[i] in obj)) 
      return false;
  }
  return true;
}

:

if (!testProps(obj, ['key', 'key2'])
   return;
+1

, "", , . - :

function opt(opt) {
    for(var i = 0; i<3; i++) {
        if(typeof opt["key"+((i > 0) ? "" : i + 1))] === "undefined") {
            return;
        }
    }

    // create object
}

opt undefined, , .

, , :

var propsToCheck = ["key", "key1", "key2"];

function(opt) {
    for(var i = 0, ii = propsToCheck.length; i<ii; i++) {
        if(typeof opt[propsToCheck[i]] === "undefined") {
            return;
        }

        // create object
    }
}

, , .

0

:

function validate(o, args) {
    if (typeof(o) == 'object' && args instanceof Array) {
        for (var i = args.length - 1; i >= 0; --i) {
            if (typeof(o[args[i]]) === 'undefined') return false;
        }
        return true;
    } else {
        return false;
    }
}

function myFunction(obj) {
    if (validate(obj, ['foo', 'bar'])) {
        // Your code goes here.
    } else {
        // Object passed to the function did not validate.
    }
}

: http://jsfiddle.net/reL2g/

0

All Articles