简体   繁体   中英

Can I put one-line instructions in function array?

I don't know if I'm clear, but what I'm trying to do is something like this:

 ajaxUpdate= $.ajax({
                        url: "updateSheet.php",
                        type: "post",
                        data: {
                            'update': 1,
                            'id': $('#numbah'+numbah+'').attr("class"),
                            'x': if (x) x,
                            'y': if (y) y,
                            'title': if (title) title,
                            'content': if (content) content
                        }
                    });

is something like 'x': if (x) x, correct? I can't risk running this part of code corrupted, because it can mess with my file.

Just use the ternary operator and do x ? x : '' x ? x : '' . This says if x is truthy (in your case if it's set) then return x otherwise return the empty string. So you could do something like this:

ajaxUpdate= $.ajax({
                    url: "updateSheet.php",
                    type: "post",
                    data: {
                        'update': 1,
                        'id': $('#numbah'+numbah+'').attr("class"),
                        'x': x ? x : '',
                        'y': y ? y : '',
                        'title': title ? title : '',
                        'content': content ? content : ''
                    }
                });

Javascript has a three-way-operator ?: which you could use like so:

title: title ? title : '',
content: content ? content : ''

This sends an empty string, if the variable is empty or the content of it if not.

Alternatively, you can use the logical OR operator || :

title: title || ''
content: content || ''

It's a little shorter.

You can use ternary operator - info MDN

ajaxUpdate= $.ajax({
                    url: "updateSheet.php",
                    type: "post",
                    data: {
                        'update': 1,
                        'id': $('#numbah'+numbah+'').attr("class"),
                        'x': x == someValue ? x: '',
                        'y': y == someValue ? y: '',
                        'title': if (title) title,
                        'content': if (content) content
                    }
                });

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