不理解为什么在javascript中我的if语句要到错误的行

Not understanding why in javascript my if statement is going to the wrong line

本文关键字:错误 语句 if 为什么 javascript 我的 不理解      更新时间:2023-09-26

我目前有一个if语句,检查目标是否为空,如果目标不为空,然后检查目标是否为'select…"。如果它不是null和'select…’然后我想让它执行代码。当我运行这段代码时,它总是跳过if语句体的第一行,转到第二行。我不明白为什么。在本例中,它总是转到targetValue = getTargetValue();

if (target != null && !(target.lastIndexOf('select...          ', 0) === 0))
    {
        permalink.href += "&Target=" + target;
        targetValue = getTargetValue();
    }

我不确定我是否有逻辑错误。我正在使用firefox调试器并逐步完成此代码。

可能是lastIndexOf的问题,因为它从给定的索引向后搜索。在你的例子中,你给它赋值0它肯定会返回-1

lastIndexOf()方法返回给定对象所在的最后一个索引元素可以在数组中找到,如果不存在则为-1。的数组从fromIndex开始向后搜索。

尝试不带任何参数

if (target != null && !(target.lastIndexOf('select...          ') === 0))
    {
        permalink.href += "&Target=" + target;
        targetValue = getTargetValue();
    }