简单的javascript IF语句 - 正确的语法是什么

Simple javascript IF statement - what is the correct syntax?

本文关键字:语法 是什么 语句 javascript IF 简单      更新时间:2023-09-26

假设我有这个网址:

www.example.com/product-p/xxx.htm

以下 JavaScript 代码从 URL 中挑选出短语product-p

urlPath = window.location.pathname; 
urlPathArray = urlPath.split('/'); 
urlPath1 = urlPathArray[urlPathArray.length - 2];

然后,我可以使用document.write来显示短语product-p

document.write(''+urlPath1+'')

我的问题是...

如何创建一个 IF 语句,如果 urlPath1 = 'product-p' 那么 document.write (something),else document.write (blank)?

尝试这样做,但我的语法可能是错误的(我不太擅长 JS)。

我最初认为代码是这样的:

<script type="text/javascript"> 
urlPath=window.location.pathname; 
urlPathArray = urlPath.split('/'); 
urlPath1 = urlPathArray[urlPathArray.length - 2]; 
if (urlPath1 = "product-p"){
    document.write('test'); 
}
else {
    document.write(''); 
}
</script>
if (urlPath1 = "product-p")
//           ^ single = is assignment

  应该是:

if (urlPath1 == "product-p")
//           ^ double == is comparison

请注意:

document.write(''+urlPath1+'')

应该简单地:

document.write(urlPath1)

您正在用两个空字符串连接urlpath字符串...它没有多大作用。