【问题标题】:how to retrieve key and value from object search?如何从对象搜索中检索键和值?
【发布时间】:2022-01-06 20:33:51
【问题描述】:

function pageKeywords(searchValue){
  const pageKeywords = {
    "home": "/homepage",
    "about": "/about-us",
    "about us": "/about-us"
  }
  const getInputVal = searchValue;
  
  if (pageKeywords[getInputVal]) {
    console.log(pageKeywords[getInputVal])
    window.location.href = pageKeywords[getInputVal];
  } else {
    console.log('not found')
  }
}

                

$(document).ready(function(){
  $("#searchKeywords").on("keypress", function(e) {
    if (e.which === 13) {
      pageKeywords($(this).val())
    }
  });
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<input type="text" id="searchKeywords">

我想通过输入查找页面 url。我有一个包含关键字和网址的对象。然后回车时会做检查,如果关键字相同或存在,则显示url,否则显示未找到。

例如在输入中我输入“home”,当我输入时会显示 url “/homepage”,因为关键字存在,如果我输入“contact”,它会显示未找到,因为关键字不存在存在。

我已经制作了如下代码,但为什么找不到呢?

$(document).ready(function(){
  $("#searchKeywords").on("keypress", function(e){
    if(e.which == 13){   
      const map = {
        "home" : "/homepage",
        "about" : "/about-us"
      }

      const searchVal = $("#searchKeywords").val()

      Object.entries(map).map((k,v) => {
        if(searchVal == k[0]){
          console.log(k[1])
        }else{
          console.log("not found")
        }
      });
    }
  });
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<input type="text" id="searchKeywords">

【问题讨论】:

  • 熟悉how to access and process nested objects, arrays or JSON 并使用Object 的可用静态和实例方法。请注意,您尝试使用Array 的那些;您似乎将普通对象与数组混淆了。你试过pageKeywords[$(this).val()]和pageKeywords.hasOwnProperty($(this).val())吗?
  • map() 将在浏览器开发工具控制台中抛出错误。你没有提到任何错误。该错误消息也可用于进行网络搜索,可能会给你一个很大的线索
  • 我在@SebastianSimon 上方编辑了我的描述和代码

标签: javascript jquery object javascript-objects


【解决方案1】:

这里pageKeywords 是一个对象。所以你可以直接检索key,而不需要使用map和Object.entries。另请注意,您可以在按键事件侦听器之外初始化对象,并且更喜欢使用 === 而不是 ==

$(document).ready(function() {

  const pageKeywords = {
    "home": "/homepage",
    "about": "/about-us"
  }

  $("#searchKeywords").on("keypress", function(e) {
    if (e.which === 13) {
      const getInputVal = $(this).val().toLowerCase();
      if (pageKeywords[getInputVal]) {
        console.log(pageKeywords[getInputVal])
      } else {
        console.log('not found')
      }
    }
  });
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<input type="text" id="searchKeywords">

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-11-15
    • 2014-05-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-05
    相关资源
    最近更新 更多