Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

datatypes and javascript... what a nightmare

So..

I am passing data to a function that handles strings and numbers differently.

I would LIKE to be able to pass an array of values and detect what the types of each value is.

row[0] = 23;
row[1] = "this is a string... look at it be a string!";
row[2] = true;

$.each(row, function(){
  alert(typeof(this));
  //alerts object
});

Is it possible to detect the "actual" datatypes in a given row?

like image 911
Derek Adair Avatar asked Feb 28 '23 13:02

Derek Adair


2 Answers

Try

var row = [ 23, "this is a string", true ];

$.each(row, function (index,item) {
    alert(typeof(item));
});

// Alerts "number", "string", "boolean"

Whenever possible I try to avoid using "this" in callbacks and using explicit arguments is usually clearer and more predictable.

like image 183
Rich Avatar answered Mar 12 '23 10:03

Rich


@Rich suggested the best possible solution - use values passed to callback as arguments. Quote from jQuery doc:

The value can also be accessed through the this keyword, but Javascript will always wrap the this value as an Object even if it is a simple string or number value.

this.valueOf() might help you to "go back" to primitive value. But still - in that specific example it's better to use values passed as function arguments.

like image 20
Tomasz Elendt Avatar answered Mar 12 '23 10:03

Tomasz Elendt