jquery - What's the best way to sort function inputs based on type in Javascript? -


i've got function several inputs, optional in calling function. each input of different type, such string, array, or number. code this:

function dostuff(str, arr, num){     if typeof(str) != 'undefined' { $('#stringdiv').text(str)}      if typeof(arr) != 'undefined' {         for(var i=0; < arr.length; i++){             $('<li>').text(arr[i]).appendto('#arrayul')         }     }      if typeof(num) != 'undefined' { $('#numberdiv').text(num)} }  jquery(document).ready(function() {     dostuff("i'm string", [1,2,3,4,5], 7) }) 

i can account fact arguments might optional, not fact that, if missing arr, numeric argument (num) come second, not third.

to around this, can dump inputs array, , sort through array , of each type, in this fiddle. seems sloppy, and, based on number of libraries i've seen in functions, seems there's better way. there better way this? or looping through arguments , hunting types best bet?

you leave off parameters , use arguments list see passed.

but, better approach create object this:

{     str: "i'm string",     arr: [1, 2, 3, 4],     num: 3.14 } 

and inspect object keys:

function dostuff(args):     if ('str' in args) {         $('#stringdiv').text(args.str);     } 

Comments

Popular posts from this blog

android - getbluetoothservice() called with no bluetoothmanagercallback -

sql - ASP.NET SqlDataSource, like on SelectCommand -

ios - Undefined symbols for architecture armv7: "_OBJC_CLASS_$_SSZipArchive" -