我正在将Vue过滤器功能用作字符串助手,但遇到了一个有趣的问题。我觉得好像有一个简单得多的解决方案,但是无法在我的生命中提出一个解决方案或在SO中找到类似的问题。
该函数传入一个用户对象,该对象可以包含一个city
,state
和country
值。这是当前的样子:
Vue.filter('userLocation', function(user) {
const { city, state } = user;
if (city && state) {
return `${city}, ${state}`;
} else if (!city && state) {
return `${state}`;
} else if (city && !state) {
return `${city}`;
} else {
return 'Please update your location settings!';
}
});
当前,此功能仅返回城市和州的值,并且已经很丑陋,但是现在我也想添加国家/地区,这只会使它变得更加复杂。
本质上,我希望函数返回三个值的任意组合。因此,如果不包括国家,请返回城市和州。如果不包括州,则返回城市和国家等。是否有一个更好的(可能是ES6)解决方案来说明所有情况,而不是编写那么多的if / else条件语句?
答案 0 :(得分:3)
您可以执行一些技巧,但是一旦获得了类似的三项,我可能会使用数组:
Vue.filter('userLocation', function(user) {
const { city, state, country } = user;
return [city, state, country].filter(Boolean).join(", ") || 'Please update your location settings!';
});
或
Vue.filter('userLocation', function(user) {
return [user.city, user.state, user.country].filter(Boolean).join(", ") || 'Please update your location settings!';
});
“来自用户的字符串”位的实时示例:
function example(user) {
return [user.city, user.state, user.country].filter(Boolean).join(", ") || 'Please update your location settings!';
}
function test(user) {
console.log(example(user));
}
test({
city: "Dallas",
state: "Texas",
country: "USA"
});
test({
city: "San Francisco"
});
test({
city: "Denver",
state: "Colorado"
});
test({
state: "Michigan"
});
test({
city: "Middlesborough",
country: "UK"
});
test({
});
这些工作原理:
[city, state]
创建一个数组。.filter(Boolean)
从中过滤出所有 fassy 值(例如空白字符串)。结果数组将具有零个,一个或两个条目。.join(", ")
将以逗号和空格作为分隔符的条目连接起来。如果条目少于两个,则不会有任何分隔符。|| '...'
如果左侧操作数为假(例如空字符串),则使用右侧操作数。 (有关我贫乏的小博客的更多信息:JavaScript's curiously-powerful ||
operator。)您可能希望将.trim()
和city
放在state
上,以防它们仅包含空格。