JavaScript:使用'或'语句声明VAR

时间:2011-09-19 05:45:54

标签: javascript if-statement

代码是这样的

var $page_products = $page_name == 'products-uninterruptible-power-supply.php' OR 'products-uninterruptible-power-supply-np2031.php';

我已经尝试过使用

var $page_products = $page_name == 'products-uninterruptible-power-supply.php' || 'products-uninterruptible-power-supply-np2031.php';

但它仍然无效。提前谢谢!

3 个答案:

答案 0 :(得分:1)

假设您的意图是声明一个变量$page_products,如果$page_name等于这两个字符串中的任何一个,则将其设置为true,否则为false,请执行以下操作:

var $page_products = $page_name == 'products-uninterruptible-power-supply.php'
           || $page_name == 'products-uninterruptible-power-supply-np2031.php';

编辑:我刚注意到两个页面名称都以相同的四个单词开头,所以不是与每个字符串进行比较,而是适合您测试$page_name中的值是否以这些单词开头,例如:< / p>

var $page_products =
           $page_name.indexOf('products-uninterruptible-power-supply') === 0;

答案 1 :(得分:1)

这应该有效

var $page_products = ($page_name == 'products-uninterruptible-power-supply.php' || $page_name == 'products-uninterruptible-power-supply-np2031.php');

答案 2 :(得分:1)

如果要有条件地分配文件名,那么您将需要三元运算符:

var $page_products = ($page_name == 'products-uninterruptible-power-supply.php') ?
    'products-uninterruptible-power-supply.php' : 
    'products-uninterruptible-power-supply-np2031.php';