如何为li元素的每一个赋予array [i] [0]?

时间:2018-10-21 15:24:31

标签: javascript arrays object foreach prototype

我的代码的基本概念是,当我将li元素之一悬停时,该函数将在li的索引和数组的索引之间进行比较。当这些匹配时,array的元素就会显示在li的元素上。

我的期望是如果数组包含/具有任何其他数组,例如这种形式[... 'Whale', ['Dog', 'Wolf']],则li元素仅在内部div中显示0 (在我的情况下,{creatures[i][0]。)因此最终形式将类似于0-0、1-1、2-2 [0],3-3 [0],然后继续。

function customArray() {
  var array = Object.create(Array.prototype);
      array = Array.apply(array, [null, ...arguments]);
  return (array);
}

var creatures = new customArray([
    ['Seal', 'Whale', ['Dog', 'Wolf', 'Hound'], ['Cat', 'Lion', 'Jaguar'], 'Bear'],
    ['1', '2', ['3', '30', '300'], ['4', '40', '400'], '5']
]);

  $('div ul li').on('mouseenter', function() {
    var i = $(this).index() + 1;
        j = i;
    creatures.forEach((items, index) => {
      var breakPoint = Array.isArray(items), result;
      result = (breakPoint) ? true : false;
      if (i = j) {
        for(n = 0; n < creatures.length + 1; n++) {
          if(result) {
            $('nav ul li:nth-child('+ n +')').html(items[i-1][0]);
          } else {
            $('nav ul li:nth-child('+ n +')').html(creatures[i]);
            console.log('false')
          }
        }
      }
    })
  })
  * {
    margin: 0;
  }
   div {
     position: relative;
     width: 100%;
     height: 100px;
     opacity: 0.5;
     display: flex;
     flex-flow: row;
     z-index: 1;
   }
   ul {
     display: flex;
   }
   li {
     display: flex;
     flex-flow: column;
     justify-content: center;
     list-style: none;
     color: white;
     padding: 0 20px;
   }
   nav {
     position: relative;
     width: 100%;
   }
   .black {
     background-color: black;
   }
   .orange {
     background-color: orange;
   }
<div class="black">
  <ul>
    <li>menu 1</li>
    <li>menu 2</li>
    <li>menu 3</li>
    <li>menu 4</li>
    <li>menu 5</li>
  </ul>
</div>
<nav class="orange">
  <ul>
    <li>smenu 1</li>
    <li>smenu 2</li>
    <li>smenu 3</li>
    <li>smenu 4</li>
    <li>smenu 5</li>
  </ul>
</nav>
    
<script src="http://code.jquery.com/jquery-3.3.1.js"></script>

这是有问题的代码,它弹出显示Cannot read property '0' of null at forEach.creature.的错误。

任何提示都会很有趣。

谢谢。

0 个答案:

没有答案