0

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.

  • 1
    Second issue is exact dupe of https://stackoverflow.com/questions/34361379/arrow-function-vs-function-declaration-expressions-are-they-equivalent-exch – CertainPerformance Oct 18 '18 at 07:58
  • Please don't ask 2 questions in 1. Please update your question to remove the second part and ask a second question if needed (though you already have a duplicate for that). – freedomn-m Oct 18 '18 at 08:17
  • @freedomn-m I thought it could be spam when if I ask all my questions one by one, sorry. – Patrick the Star Oct 18 '18 at 09:43

1 Answers1

1

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);
})
Nitish Narang
  • 4,124
  • 2
  • 15
  • 22
  • So the second issue is, there's no way to get `this` keyword from es6 function style? – Patrick the Star Oct 18 '18 at 09:47
  • Arrow functions treat "this" differently (because of lexical scoping) than normal es5 functions, which in your scenario does not solve the purpose. I would highly recommend reading the link in my answer to get better understanding of where to not use Arrow functions Note - Arrow functions are not there to replace normal es5 functions, especially when using "this" keyword. – Nitish Narang Oct 18 '18 at 09:50
  • 1
    Thanks for answering and commenting my issue. – Patrick the Star Oct 18 '18 at 09:53