gpt4 book ai didi

javascript - 可以像这样使用简写条件来构建字符串吗?

转载 作者:行者123 更新时间:2023-11-30 14:17:32 26 4
gpt4 key购买 nike

我正在尝试根据下拉列表选择向我的 URL 添加一些参数,我希望代码尽可能简短,因此我正在尝试为参数构建一个字符串,以省略任何空白变量所以它们不会附加到 URL 字符串。以下是我尝试过的:

$(function() {
var product = 'shirt',
size = 'large',
color = 'blue',
custom = '';

var urlParams = (product === '') ? '' : 'product=' + product + '&' + (size === '') ? '' : 'size=' + size + '&' + (color === '') ? '' : 'color=' + color + '&' + (custom === '') ? '' : 'custom=' + custom;

console.log(urlParams);

// Go to results page
// location.href = 'results?' + urlParams;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

urlParams 的预期输出是:

product=shirt&size=large&color=blue

不幸的是,这会返回一个空字符串。是否可以像这样构建参数?还是有更好的方法来实现这一点?

最佳答案

括号很重要!

问题是,您没有研究旧的。 custom === "" 变得真实,然后你的整个条件就崩溃了。更好的方法是:

(function() {
var product = 'shirt',
size = 'large',
color = 'blue',
custom = '';

var urlParams = ((product === '') ? '' : 'product=' + product) + '&' + ((size === '') ? '' : 'size=' + size) + '&' + ((color === '') ? '' : 'color=' + color) + '&' + ((custom === '') ? '' : 'custom=' + custom);

console.log(urlParams);

// Go to results page
// location.href = 'results?' + urlParams;
})();

现在您可以看到有&。更好的版本是:

(function() {
var product = 'shirt',
size = 'large',
color = 'blue',
custom = '';

var urlParams = ((product === '') ? '' : 'product=' + product) + '&' + ((size === '') ? '' : 'size=' + size) + '&' + ((color === '') ? '' : 'color=' + color) + '&' + ((custom === '') ? '' : 'custom=' + custom);
urlParams = urlParams.replace(/^\&+|\&+$/g, '');
console.log(urlParams);

// Go to results page
// location.href = 'results?' + urlParams;
})();

最好的方法是使用数组和 .join()s。

(function() {
var product = 'shirt',
size = 'large',
color = 'blue',
custom = '';

var urlParams = [
((product === '') ? '' : 'product=' + product),
((size === '') ? '' : 'size=' + size),
((color === '') ? '' : 'color=' + color),
((custom === '') ? '' : 'custom=' + custom)
];
urlParams = urlParams.join("&").replace(/^\&+|\&+$/g, '');
console.log(urlParams);

// Go to results page
// location.href = 'results?' + urlParams;
})();

关于javascript - 可以像这样使用简写条件来构建字符串吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53325222/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com