简体   繁体   English

三元运算符如何比较 JavaScript 中的字符和数字?

[英]How does the ternary operator compares characters and numbers in JavaScript?

I had to find maximum in array so I wrote a function which used for loop while also using ternary operator and I noticed that just reversing the direction of loop changes the output plus the output is also different if I use if-else.我必须在数组中找到最大值,所以我编写了一个用于循环的函数,同时还使用了三元运算符,我注意到如果我使用 if-else,只需反转循环的方向就会改变输出加上输出也不同。 Moreover, changing the position of 'a' in the array also changes the output.此外,改变 'a' 在数组中的位置也会改变输出。

 const array2 = ['a', 3, 4, 2]; function biggestNumberInArray(arr) { let max=0; for (let i = 0; i < arr.length; i++) { max = max>arr[i]?max:arr[i]; } return max; } function biggestNumberInArray2(arr) { let max=0; for (let i = arr.length - 1; i >= 0; i--) { max = max>arr[i]?max:arr[i]; } return max; } console.log(biggestNumberInArray(array2)); console.log(biggestNumberInArray2(array2));

When running the first function output is 4运行第一个函数时输出为 4

When running the second function output is 'a'运行第二个函数时,输出为 'a'

If you step through the debugger and look at the comparisions ... you'll see that comparing 'a' with any number is always false.如果您单步调试调试器并查看比较……您会发现将 'a' 与任何数字进行比较总是错误的。

That's why it seems to "work" in one direction, but not the other.这就是为什么它似乎在一个方向“工作”,而不是另一个方向。

Specifically:具体来说:

When comparing a string with a number, JavaScript will convert the string to a number when doing the comparison.将字符串与数字进行比较时,JavaScript 会在进行比较时将字符串转换为数字。 An empty string converts to 0. A non-numeric string converts to NaN which is always false .空字符串转换为 0。非数字字符串转换为 NaN ,它始终为 false 。 When comparing two strings, "2" will be greater than "12", because (alphabetically) 1 is less than 2.比较两个字符串时,“2”将大于“12”,因为(按字母顺序)1 小于 2。

Because string 'a' and integers 2,3,4 are incomparable.因为字符串'a'和整数2,3,4是不可比的。 Therefore it always returns false因此它总是返回false

In your first function, it returns 4 because 'a' is compared first and returns false , then max is assigned 3在你的第一个函数中,它返回4因为首先比较'a'并返回false ,然后max被分配3

In the second function it returns 'a' because 'a' is compared last.在第二个函数中,它返回'a'因为最后比较'a''a'

You can check if the string can be converted to number using Number() or parseInt()您可以检查字符串是否可以使用Number()parseInt()转换为数字

 const arr = ['a', 3, 4, 2]; function biggestNumberInArray2(arr) { let max=0; for (let i = arr.length - 1; i >= 0; i--) { const comparable = Number(arr[i]) || -99 max = max > comparable ? max : comparable; } return max; } console.log(biggestNumberInArray2(arr))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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