[英]ES6 .some() with the ternary operator behaves differently
I've noticed a weird behavior with .some() array method and a ternary operator. 我注意到.some()数组方法和三元运算符的行为很奇怪。
It behaves differently when the integer(count) has to be incremented on each true case with and without the curly brackets. 当在每个有和没有大括号的真实情况下必须增加integer(count)时,它的行为会有所不同。
Although, the console.log shows correct truthy on each iteration. 虽然,console.log在每次迭代中显示正确的事实。
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
为什么这个给输出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 ) 因此,在第一次迭代中,
count++
将返回0,然后将值增加1。(因为它是post增量)
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 ) 在第二次迭代中,它将返回值为
1
的true值,然后将其递增1。(由于您发现了一个true值,因此某些值将停止迭代)
Why this one is giving output 3
为什么这个给输出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)
Just add a return statement and see the changes. 只需添加一个return语句并查看更改。
let count = 0; let arr = ['011','202','3300'] arr.some(k => { return k.includes('0') ? count++ : null}); console.log(count)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.