简体   繁体   中英

Why is 10 less than 9?

I have a function switcher() which has an Object argument, video . It should log 'Start' if video.start <= video.ende . 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' .

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: addon: Start: 1
console.log: addon: End: 3
console.log: addon: Start

console.log() Failed:

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. 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.

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