简体   繁体   中英

If statement inside a Jquery loop acting odd

I have this Json object which i'm trying to loop through a jquery each function. inside of it I have an if condition to specify some values.

My JSON object is here

{
  "times": [
    {
      "visit_time": "01.30pm-01.45pm",
      "count": "3"
    },
    {
      "visit_time": "02.15pm-02.30pm",
      "count": "1"
    },
    {
      "visit_time": "02.30pm-02.45pm",
      "count": "3"
    }
  ],
  "slots": "20"
}

My code is here. 'data' catches the JSON object

function (data) {
          console.log(data);
          $.each(data.times, function(key, value) {
            console.log(value.count);
            if(value.count <= data.slots){
              console.log(data.slots);
            }

          });
        }

The console.log() as this

3 , 1 , 20 , 3

As for my understanding it should be 3 , 20 , 1 , 20 , 3 , 20

This is what i'm expecting to get from the code also. Please someone explain me why i'm wrong or what's wrong with my code is.

You need to convert your strings to numbers if you want to compare them like that. If you can't change them in the json, you'll need to convert them.

You could do something as simple as adding + directly in front of the string to convert it. There are multiple ways to convert strings to numbers, so pick the method that suits your needs.

 const stuff = { "times": [{ "visit_time": "01.30pm-01.45pm", "count": "3" }, { "visit_time": "02.15pm-02.30pm", "count": "1" }, { "visit_time": "02.30pm-02.45pm", "count": "3" } ], "slots": "20" } function t(data) { console.log(data); $.each(data.times, function(key, value) { console.log(value.count); if (+value.count <= +data.slots) { console.log(data.slots); } }); } t(stuff);
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

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