find()方法在我的vanilla javascript项目中不起作用

find()方法在我的vanilla javascript项目中不起作用,javascript,html,Javascript,Html,我一直在做一个香草javascript项目 这里的这一行const tempPage=sublinks.find({page}=>page==text)在控制台上记录为undefined const sublinks = [ { page: 'products', links: [ { label: 'payment', icon: 'fas fa-credit-card', url: 'products.html' }, { label: 'ter

我一直在做一个香草javascript项目

这里的这一行
const tempPage=sublinks.find({page}=>page==text)在控制台上记录为
undefined


const sublinks = [
  {
    page: 'products',
    links: [
      { label: 'payment', icon: 'fas fa-credit-card', url: 'products.html' },
      { label: 'terminal', icon: 'fas fa-credit-card', url: 'products.html' },
      { label: 'connect', icon: 'fas fa-credit-card', url: 'products.html' },
    ],
  },
  {
    page: 'developers',
    links: [
      { label: 'plugins', icon: 'fas fa-book', url: 'products.html' },
      { label: 'libraries', icon: 'fas fa-book', url: 'products.html' },
      { label: 'plugins', icon: 'fas fa-book', url: 'products.html' },
      { label: 'billing', icon: 'fas fa-book', url: 'products.html' },
    ],
  },
  {
    page: 'company',
    links: [
      { label: 'about', icon: 'fas fa-briefcase', url: 'products.html' },
      { label: 'customers', icon: 'fas fa-briefcase', url: 'products.html' },
    ],
  },
];

const submenu = document.querySelector('.submenu');
const linkBtns = [...document.querySelectorAll('.link-btn')];

linkBtns.forEach((btn) => {
    btn.addEventListener('mouseover', e => {
        const text = e.currentTarget.textContent;
        const tempBtn = e.currentTarget.getBoundingClientRect();
        const center = (tempBtn.left + tempBtn.right) / 2;
        const bottom = tempBtn.bottom - 3;

        // ***********this line**************************
        const tempPage = sublinks.find(({ page }) => page === text);
        // ******************************************************
        console.log(tempPage);
        
        submenu.classList.add('show');
        submenu.style.left = `${center}px`;
        submenu.style.top = `${bottom}px`;
    })
});
下面是HTML代码

<ul class="nav-links">
          <li>
            <button class="link-btn">Products</button>
          </li>
          <li>
            <button class="link-btn">Developers</button>
          </li>
          <li>
            <button class="link-btn">Company</button>
          </li>
        </ul>

<aside class="submenu">
      hello there
    </aside>
  • 产品
  • 开发者
  • 单位
你好
在HTML中:

<button class="link-btn">Products</button>
“页面”将为“产品”,“文本”将为“产品”

你可以把它改成

const tempPage = sublinks.find(({ page }) => page === text.toLowerCase())

您应该将文本转换为小写的
页面===text.toLowerCase()
,因为按钮的所有文本节点都是大写的,因此每次迭代
find()
方法时都返回false“产品”
const text=e.currentTarget.textContent.trim().toLowerCase()很高兴它有帮助:D,我建议您在进行调试时,可以尝试在find()中的函数中添加更多的console.log()。或者使用VSCode调试器进行跟踪。当您拥有大量代码和逻辑时,它确实会有所帮助。
const tempPage = sublinks.find(({ page }) => page === text.toLowerCase())