Parsing a data type variable for a function that contains conditional data type checking in JavaScript

To pass a data type that changes (from an array to an integer) to the same function, and then before changing its value, check the data type by looking at the method below 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:)

+4
source share
2 answers

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 ); 
+2
source

A more efficient way could be to split your function (if 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 will also apply the DRY principle ("do not repeat yourself") because you do not need to enter the same logic twice (i.e. x.bar = '1'; ).

+1
source

Source: https://habr.com/ru/post/1486491/


All Articles