4

To pass a datatype that varies (from an array to an integer) to the same function, and then check against the datatype before changing its value, looking at the below method using instanceof Array is there a better/more efficient way?

function foo(x) { 
  if (x instanceof Array) {
    for(i=0;i<x.length;i++){    
      x[i].bar = '1';
      x[i].baz = '2';       
    }   
  }
  else{
    x.bar = '1';
    x.baz = '2';    
  }
}

Thanks :)

2
  • Object.prototype.toString.call(x) === "[object Array]", this is an alternative method, but even yours is good Commented Jun 16, 2013 at 17:26
  • In newer browsers -> Array.isArray(x) Commented Jun 16, 2013 at 17:30

2 Answers 2

2

An alternative (using ECMAScript standard)

if( Object.prototype.toString.call( x ) === '[object Array]' ) {

    for(i=0;i<x.length;i++) {  

      x[i].bar = '1';
      x[i].baz = '2';       
    }  
}

See ECMAScript

Or if you always want it as an array, but this is not recommended

x = [].concat( x );
Sign up to request clarification or add additional context in comments.

1 Comment

The first method is what is given in ECMAScript to find the class of an object. the second method, as I said is not recommended because of performance reasons.
1

A more efficient way could also be to split up your function (if that is possible for you):

function fooArray(x) { 
    for(i = 0; i < x.length; i++){    
        foo(x[i]);   
    }   
}

function foo(x) {
    x.bar = '1';
    x.baz = '2'; 
}

This would also apply the DRY principle ("don't repeat yourself") because you don't need to code the same logic (i.e. x.bar = '1';) twice.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.