我正在尝试编写一个接受字符串列表或单个字符串的函数。如果它是一个字符串,那么我想将其转换为仅包含一项的数组,因此我可以遍历它而不必担心错误。
那么,如何检查变量是否为数组?
我整理了以下各种解决方案,并创建了jsperf测试。它们都非常快,因此只需使用Array.isArray
- 现在得到了很好的支持,并且可以跨框架使用。
If the only two kinds of values that could be passed to this function are a string or an array of strings, keep it simple and use a typeof
check for the string possibility:
function someFunc(arg) {
var arr = (typeof arg == "string") ? [arg] : arg;
}
A = [1,2,3]
console.log(A.map==[].map)
In search for shortest version here is what I got so far.
Note, there is no perfect function that will always detect all possible combinations. It is better to know all abilities and limitations of your tools than expect a magic tool.
You could is isArray method but I would prefer to check with
Object.getPrototypeOf(yourvariable) === Array.prototype
I know, that people are looking for some kind of raw javascript approach. But if you want think less about, take a look here: http://underscorejs.org/#isArray
_.isArray(object)
Returns true if object is an Array.
(function(){ return _.isArray(arguments); })();
=> false
_.isArray([1,2,3]);
=> true
https://developer.mozilla.org/zh-CN/docs/JavaScript/Reference/Global_Objects/Array/isArray
Array.isArray = Array.isArray || function (vArg) {
return Object.prototype.toString.call(vArg) === "[object Array]";
};
您可以检查变量的类型是否为数组;
var myArray=[];
if(myArray instanceof Array)
{
....
}
考虑到以下评论,这是我尝试改进此答案的尝试:
var isArray = myArray && myArray.constructor === Array;
它摆脱了if / else,并考虑了数组为null或undefined的可能性
我将提供一个功能来测试您要处理的对象的类型...
function whatAmI(me){ return Object.prototype.toString.call(me).split(/\W/)[2]; }
// tests
console.log(
whatAmI(["aiming","@"]),
whatAmI({living:4,breathing:4}),
whatAmI(function(ing){ return ing+" to the global window" }),
whatAmI("going to do with you?")
);
// output: Array Object Function String
那么您可以编写一个简单的if语句...
if(whatAmI(myVar) === "Array"){
// do array stuff
} else { // could also check `if(whatAmI(myVar) === "String")` here to be sure
// do string stuff
}
我用一种非常简单的方式来做。为我工作。有什么缺点吗?
Array.prototype.isArray = true;
a=[]; b={};
a.isArray // true
b.isArray // (undefined -> false)
这个问题只有一种解决方案
x instanceof Array
其中x是变量,如果x是数组,它将返回true,否则返回false。
简单的功能检查一下:
function isArray(object)
{
return object.constructor === Array;
}
这是所有方法中最快的方法(支持所有浏览器):
function isArray(obj){
return !!obj && obj.constructor === Array;
}
jQuery还提供了一种$.isArray()
方法:
var a = ["A", "AA", "AAA"];
if($.isArray(a)) {
alert("a is an array!");
} else {
alert("a is not an array!");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
我将首先检查您的实现是否支持isArray
:
if (Array.isArray)
return Array.isArray(v);
您也可以尝试使用instanceof
运算符
v instanceof Array
In your case you may use
concat
method of Array which can accept single objects as well as array (and even combined):concat
seems to be one of the oldest methods of Array (even IE 5.5 knows it well).