Search code examples
javascriptjqueryarraysfunctionanonymous

How to check inner arrays that inside of outer array? (Plus => function)


Sorry if these questions are one of basics in JS.

Issue 1.

I'm trying to make the code detects inner array which is inside of outer array,

and the structure of the array is something like this;

var array = ['Bob', ['Tim', 'Katy', 'Zoe'], 'Jimmy', 'Jay' . . .]

<div>
  <ul>
    <li>name goes here</li>
    <li>name goes here</li>
    <li>name goes here</li>
    <li>name goes here</li>
    <li>name goes here</li>
    <li>name goes here</li>
  </ul>
</div>

  const peeps = ['Bob', ['Tim', 'Katy', 'Zoe'], 'Jimmy', 'Jay', 'Louis', 'Yagami Light'];

  $('div ul li').on('mouseenter', function() {
    for (i = 0; i < peeps.length; i++) {
      if (peeps[i][] in peeps[i] == true) {
        console.log('wow')
      }
    }
  })

This is my progress so far but never works the way I expected.

Issue 2.

I stuck to get this keyword from arrow function.

$('div ul li').on('mouseenter', () => {
  var a = $(this).index();
  console.log(a);
})

This code keeps showing -1 for somewhat reason, but after changed the () to function() {} the code prints 1, 2, 3, 4 as I wanted.

Is there anybody know why => function can't get this keyword from that code?

Any tips or infos would be great to solve my issues.

Thanks.


Solution

  • For first issue please try using Array.isArray to check if element is an array like below -

    var peeps = ['Bob', ['Tim', 'Katy', 'Zoe'], 'Jimmy', 'Jay', 'Louis', 'Yagami Light'];
    
    peeps.forEach((d, i) => Array.isArray(d) && console.log('found an array', d))
    

    And for second one, it's an issue of "using this with Arrow functions". To solve this you can change "arrow function" to es5 function

    $('div ul li').on('mouseenter', function() {
      var a = $(this).index();
      console.log(a);
    })