简体   繁体   中英

Get values according function parameters in Javascript

I have the next function:

 const fun = (nr, car, color, obj) => { const cars = nr - 2; const colors = nr - 1; const objects = nr -3; const main = { c: `${cars}cars.`, co: `${colors}colors.`, obj: `${objects}objects.` }; console.log(car && main.c, color && main.co, obj && main.obj) return `${car && main.c || color && main.co|| obj && main.obj}`; }; console.log(fun(65, false, true, true))

How you can notice, depending by the parameters fun(65, false, true, true) i should get the correct data. In this example i should get this string 64colors. 62obj. 64colors. 62obj. , but i don't get this. So depending by the parameters i want to show the corresponding values. How to do this?

Since you are using the or operator within the string, it just returns the result till a first non falsy value and not any further. You need to split your logic into three parts to be able to create a proper string

 const fun = (nr, car, color, obj) => { const cars = nr - 2; const colors = nr - 1; const objects = nr -3; const main = { c: `${cars}cars.`, co: `${colors}colors.`, obj: `${objects}objects.` }; console.log(car && main.c, color && main.co, obj && main.obj) return `${car && main.c || ''}${color && main.co || ''}${obj && main.obj || ''}`; }; console.log(fun(65, false, true, true))

main.colors would return undefined which is falsy because it doesn't exist in the main object.

And the OR || operator doesn't return more than one value.

I changed the return statement so you can get 64colors62objects

 const fun = (nr, car, color, obj) => { const cars = nr - 2; const colors = nr - 1; const objects = nr -3; const main = { c: `${cars}cars.`, co: `${colors}colors.`, obj: `${objects}objects.` }; return `${car && main.c? main.c: ''}${color && main.co? main.co: ''}${obj && main.obj? main.obj: ''}`; }; console.log(fun(65, false, true, true))

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