0

here is a part of js code where i am trying to check this condition what if it has data but not of the right type or value? it already has this if condition can you guys tell me how to chk it providing my code below..

setcurrentFruit : function (fruitName, currentFruit) {
            WorklistStorage.set(fruitName, currentFruit, false);
        },
        getcurrentFruit : function (fruitName) {
            var currentFruit = unescapeJSON(WorklistStorage.get(fruitName, false));
            **if (currentFruit == "undefined" || typeof currentFruit == "undefined") {**
                var date = new Date();
                currentFruit = date.toString();
                wholeQueue.setcurrentFruit(fruitName, currentFruit);
                //console.log("poppppp");
            }
            currentFruit = new Date(currentFruit);
            return currentFruit;
        },
  • What is the right type or value? – tymeJV Sep 18 '13 at 19:12
  • i am trying to put the one check to data type of for currentFruit it is date type or not –  Sep 18 '13 at 19:19
  • 1
    See http://stackoverflow.com/questions/643782/how-to-know-if-an-object-is-a-date-or-not-with-javascript – mccannf Sep 18 '13 at 19:23
  • @mccannf: thanks for ur reply...i looked into it..but can u tell me how to update in my code its confusing –  Sep 18 '13 at 19:41

1 Answers1

2

This is what underscore does::

if (toString.call(currentFruit) === '[object String]') {
  // is string
}

http://underscorejs.org/underscore.js

search for toString

Here's a jsfiddle: http://jsfiddle.net/btipling/U7PRq/

My jsfiddle uses forEach which does not work in all browsers.

Note you can replace [object String] with [object Date] or other types. See underscore's source, or try it in console.log:

toString.call(new Date())
"[object Date]"
Bjorn
  • 69,215
  • 39
  • 136
  • 164
  • thanks for ur reply...can u include it in my code since underscore is confusing –  Sep 18 '13 at 19:24
  • Replace **if (currentFruit == "undefined" || typeof currentFruit == "undefined") {** with if(!toString.call(currentFruit) !== '[object Date]') { – Bjorn Sep 18 '13 at 19:26
  • @BjornTipling How does your answer and related fiddle relate to underscore? In your fiddle, I checked the External Resources tab and underscore.js is not being loaded. So, does your code work without underscore.js and if so why mention it? (I am curious, not critical or nit-picking) – cssyphus Sep 18 '13 at 19:37
  • I used the mechanism underscore uses to check. Like I looked at the source code of what underscore does, and used that for this answer. I did not use underscore itself. So it works without underscore, I simply mentioned underscore to give credit for the actual source of the answer. – Bjorn Sep 18 '13 at 20:03
  • @BjornTipling: thanks for ur reply...i used this line if(!toString.call(currentFruit) !== '[object Date]') { but its showing this error object doesn't support property or method call... –  Sep 18 '13 at 20:32