“如何告诉javascript”;任何大于“的数字;关于三元算子?
我需要建立一个带条件的三元运算符:每当URL是/index/加上任何大于“1”的数字时,X都是 我试过这个(带“to”的字符串:“如何告诉javascript”;任何大于“的数字;关于三元算子?,javascript,spring,ternary-operator,gatsby,Javascript,Spring,Ternary Operator,Gatsby,我需要建立一个带条件的三元运算符:每当URL是/index/加上任何大于“1”的数字时,X都是 我试过这个(带“to”的字符串: <Spring from={{ height: location.pathname === '/' ? '0vh' : '0vh' }} to={{ height: (location.pathname === '/' || location.pathname === '/index/' + (>= 2) ) ? '36vh' : '0vh
<Spring
from={{ height: location.pathname === '/' ? '0vh' : '0vh' }}
to={{ height: (location.pathname === '/' || location.pathname === '/index/' + (>= 2) ) ? '36vh' : '0vh' }}
>
=2))?'36vh':'0vh'}
>
不幸的是,它不起作用。
这是为了分页问题(我不知道将创建多少页)。这与条件运算符无关。它与匹配字符串有关。如果要将
location.pathname
与/index/n
匹配,其中n
必须大于1,则可能需要正则表达式:
/\/index\/(?:[2-9]|\d{2,})/.test(location.pathname)
(?:…)
是非捕获组。[2-9]|\d{2,}
是一个替代项,与[2-9]
或\d{2,}
匹配<代码>[2-9]匹配2到9之间的任何数字<代码>\d{2,}匹配两个或多个数字
在这方面:
<Spring
from={{ height: location.pathname === '/' ? '0vh' : '0vh' }}
to={{ height: (location.pathname === '/' || /\/index\/(?:[2-9]|\d{2,})/.test(location.pathname) ) ? '36vh' : '0vh' }}
>
这与条件运算符无关。它与匹配字符串有关。对不起,我如何将其添加到字符串中?这样行吗<代码>。。。location.pathname=='/'| | location.pathname==`${/\/index\/(?:[2-9]\d{2,})/`?..我正在尝试不同的组合,但它们不起作用。非常感谢!它起作用了。我仍然没有使用测试(location.pathname)
,每当我使用正则表达式时是否有必要?在初始条件(?)@Santiago-test中使用location.pathname是正则表达式的一种方法,如果您不需要匹配对象,它通常是最佳选择。您可以执行location.pathname.match(/…/)!=null
,但它会创建一个匹配对象,您只能使用该对象进行是/否决策。test
会返回一个布尔值。