简体   繁体   English

为什么10小于9?

[英]Why is 10 less than 9?

I have a function switcher() which has an Object argument, video . 我有一个功能switcher() ,它有一个Object参数video It should log 'Start' if video.start <= video.ende . 如果video.start <= video.ende ,则应记录为'Start' It's working fine in most cases (example: video.start = 1 and video.ende = 3 ), but when video.start = 9 and video.ende = 10 it logs 'End' . 在大多数情况下,它运行良好(例如: video.start = 1video.ende = 3 ),但是当video.start = 9video.ende = 10它将记录为'End'

function switcher(video)   
{
    console.log("Start: " + video.start);
    console.log("End: " + video.ende);

    if(video.start <= video.ende) // Not working correctly
    {
        console.log("Start");
    }
    else
    {
        console.log("End");
    }
}

console.log() successes: console.log()成功:

console.log: addon: Start: 1
console.log: addon: End: 3
console.log: addon: Start

console.log() Failed: console.log()失败:

console.log: addon: Start: 9
console.log: addon: End: 10
console.log: addon: End

Why is it so? 为什么会这样呢?
How can I fix this? 我怎样才能解决这个问题?

It sounds like video.start and video.ende are strings, not numbers, so they're being compared lexicographically, not numerically. 听起来video.startvideo.ende是字符串,而不是数字,所以按字典顺序而不是数字进行比较。 Convert them to numbers before comparing. 比较之前将它们转换为数字。

if (Number(video.start) <= Number(video.ende))

Or you can fix the code that creates the video object so it converts to a number at that time. 或者,您可以修复创建video对象的代码,以便在那时将其转换为数字。

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

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