JavaScript对象中的线性搜索

Linear Searching in a JavaScript Object

本文关键字:线性搜索 对象 JavaScript      更新时间:2023-09-26

我正试图创建一堆JS对象,并将它们全部放入一个数组中,以便能够线性搜索每个对象中包含的值。

我很确定这个问题是在搜索传入的值时出现在嵌套的for循环中。我研究了.contains()方法,只使用了简单的比较运算符==和===,但它们都不适用。所以我的问题是,当我在文本框中键入"times square"时,目前,我只想弹出警报框,并在POI数组中显示包含该目的地的对象的名称。

我下面的HTML只是一个简单的文本框和一个提交按钮。有什么帮助吗?

// scripts
var bmtBroadWayLine = {
      color: 'yellow',
      poi: ["times square", 'south ferry'],
      letters: 'N Q R',
      name: "BMT Broadway Line",
};
var destinations = [];
destinations[1] = bmtBroadWayLine;
function findDestination() {
      for (var i = 0; i < destinations.length; i++) {
            for (var j = 0; j < destinations[i].poi.length; j++) {
                  if (destinations[i].poi[j] == document.getElementById("dest-entry")) {
                        alert(destinations[i].poi[j].name);
                  }
            }
      }
}
<!DOCTYPE html>
<html>
      <head>
            <meta charset="utf-8">
            <title>Routes</title>
      </head>
      <body>
            <h1>Where Do You Want To Go?</h1>
            <input type="text" id="dest-entry">
            <input type="button" value="Send" onclick="findDestination()">
            <div id="output"></div>
            <script src="scripts.js"></script>
      </body>
</html>

这个脚本有很多错误:

  • 您正在比较字符串和DOM对象
  • 您正试图访问字符串的name属性
  • 您正在使用基于零的索引语言中的基于1的索引

没有错误,但仍然:

  • 您没有验证null
  • 您在每次迭代中都要查找一个DOM项,这很慢

您正在将字符串与DOM对象进行比较。

if (destinations[i].poi[j] == document.getElementById("dest-entry")) {
    alert(destinations[i].poi[j].name);
}

相反,将其与DOM对象中的字符串值进行比较:

if (destinations[i].poi[j] == document.getElementById("dest-entry").value) {
    alert(destinations[i].poi[j].name);
}

可能还想检查此document.getElementById("dest-entry")NULL

此外,您正在访问stringname属性

alert(destinations[i].poi[j].name);

你可能只是想要这个:

alert(destinations[i].name);

还有:

destinations[1] = bmtBroadWayLine;

只需进行

destinations.push(bmtBroadWayLine);

添加索引不是第一个可用的项时,长度会增加1以上。所以现在有了1个元素,长度是2,第一个元素是未定义的,您正试图访问undefined的属性。