I would like to separate the processing according to whether the values in the variables in JavaScript are strings or strings.
You don't have to check if the array is exactly a string.
var stringOrArray=someFunc();
if(argumentIsString(stringOrArray)){
// What happens when a string is passed?
} else if(argumentIsArray(stringOrArray)) {
// What to do when an array is passed?
}
What will happen to argumentIsString
, argumentIsArray
above?
If you know one of them, else
is fine for the other, but if possible, I would like to decide on each string and array in consideration of future changes.
By the way, IE8 or higher is required.
javascript
I think this will be helpful.
JavaScript Garden
Japanese translation
function is(type,obj){
varclas=Object.prototype.toString.call(obj).slice(8,-1);
return obj!== undefined&obj!==null&clas===type;
}
is('String', 'test'); // true
is('String', new String('test')); // true
Not very versatile, but
Is this the way to make it easy?
var stringOrArray=someFunc();
if(typeof(stringOrArray)=="string"||stringOrArray instanceof String){
// What happens when a string is passed?
} else if (stringOrArray instance of Array) {
// What to do when an array is passed?
}
[Additional]
It has already been mentioned in the comments in the other answers,
If the Array or String itself is overwritten, this method will fail.
The method is very simple, and before deciding,
/*The contents of foo and bar are appropriate*/
String=foo
Array=bar
If it says , it is out.
If you look at the undercore.js source, you compare the returned strings by Object.prototype.toString.call(v)
.
Object.prototype.toString.call(obj)==='[object Array]'
Object.prototype.toString.call(obj)==='[object String]'
# Why do I do this? instanceof
is enough, but
I had a similar question at home
https://stackoverflow.com/questions/1058427/how-to-detect-if-a-variable-is-an-array
I wonder if Array.isArray
can be used in IE8...?
© 2024 OneMinuteCode. All rights reserved.