简体   繁体   中英

How to build a function when parameters are combination of string and array(object) in javascript?

I'm reading values from excel and then trying to build a function based on parameters it has.

It will have dynamic parameters in combination of strings and arrays as per its usage in function.

My sample code as below

excel

A1 = 'test'
A2 = ['test1','test2']

JS

function test(params){
..
var paramValues = params.split(","); //params1=A1, params2=A2 here params is sheet name
    if(paramValues != null)
    {
        for(var pi = 0;pi<paramValues.length;pi++)
        {
            index = paramValues[pi].substring(6) //returns value of row number as index
            var paramCellVal = await excel.getCellValue("A"+index) //returns 'test' in iteration 1,['test1','test2'] in iteration 2
            actualParams.push(paramCellVal) //push values to array
        }
        console.log(actualParams+"actualParams"+typeof(actualParams)) //returns object
        action =  findFunction(...actualParams);
    }
    else
    {
        ...
    }
}

function findFunction(...actualParams){
    run(...actualParams)
}

function run(param1, param2){
console.log(param1, typeof(param1))
console.log(param2, typeof(param2))
console.log(param2[0], typeof(param2[0]))
console.log(param2[0], typeof(param2[1]))
}

expected output:

'test', string
['test1','test2'], object
'test1', string
'test2', string

actual output:

'test', string
['test1','test2'], string
[, string
', string

My expectation is to build dynamic function with different set of variables, hence used spread syntax.

function run(param1, param2){
console.log(param1, typeof(param1))
console.log(JSON.stringify(param2), typeof(JSON.stringify(param2)))
console.log(JSON.stringify(param2[0]), typeof(JSON.stringify(param2[0])))
console.log(JSON.stringify(param2[1]), typeof(JSON.stringify(param2[1])))
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM