简体   繁体   中英

ES6 .some() with the ternary operator behaves differently

I've noticed a weird behavior with .some() array method and a ternary operator.

It behaves differently when the integer(count) has to be incremented on each true case with and without the curly brackets.

Although, the console.log shows correct truthy on each iteration.

Any thoughts?

> let arr = ['011','202','3300']
undefined
> let count = 0;
undefined
> arr.some(k => k.includes('0') ? count++ : null);
true
> count;
2 // is not correct
> count = 0;
0
> arr.some(k => {k.includes('0') ? count++ : null});
false
> count;
3 // correct 
>
> arr.some(k => {k.includes('0') ? console.log('true') : null});
true
true
true
false
> arr.some(k => k.includes('0') ? console.log('true') : null);
true
true
true
false

Let's understand this

Why this one is giving output 2

arr.some(k => k.includes('0') ? count++ : null);

 let count = 0; let arr = ['011','202','3300'] arr.some(k => k.includes('0') ? count++ : null); console.log(count) 

  • So on first iteration count++ will return 0 and than increment value by 1. ( since it is post increment )

  • On second iteration it will return value as 1 which is true and than increment by 1. ( since you found one true value some will stop iteration )

Why this one is giving output 3

arr.some(k => {k.includes('0') ? console.log('true') : null});

 let count = 0; let arr = ['011','202','3300'] arr.some(k => {k.includes('0') ? count++ : null}); console.log(count) 

  • Here you're not utilizing implicit return of arrow function so on each iteration you're eventually returning undefined. so your some will iterate through all the elements and you get output as 3.

Just add a return statement and see the changes.

 let count = 0; let arr = ['011','202','3300'] arr.some(k => { return k.includes('0') ? count++ : null}); console.log(count) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM