检查对象数组? [英] Check if object is array?
问题描述
我想写一个不接受字符串列表,或者一个字符串的函数。如果它是一个字符串,那么我想它只是一个项目转换为数组。那么我可以遍历它,不用担心出错。
I'm trying to write a function that either accepts a list of strings, or a single string. If it's a string, then I want to convert it to an array with just the one item. Then I can loop over it without fear of an error.
那么,如何检查是否变量是一个数组?
So how do I check if the variable is an array?
我围捕以下各种解决方案,并创建了一个 jsperf测试。
I've rounded up the various solutions below and created a jsperf test.
推荐答案
要找到类对象在ECMAScript标准给出的方法是使用的toString
方法从的Object.prototype
。
The method given in the ECMAScript standard to find the class of Object is to use the toString
method from Object.prototype
.
if( Object.prototype.toString.call( someVar ) === '[object Array]' ) {
alert( 'Array!' );
}
或者你可以使用的typeof
来测试,如果它是一个字符串:
Or you could use typeof
to test if it is a String:
if( typeof someVar === 'string' ) {
someVar = [ someVar ];
}
或者,如果你不关心性能,你可以只是做一个 CONCAT
到一个新的空Array。
Or if you're not concerned about performance, you could just do a concat
to a new empty Array.
someVar = [].concat( someVar );
编辑:查看了彻底治疗从<一个 HREF =http://stackoverflow.com/users/157247/tj-crowder> @TJ克罗德的博客,如张贴在低于他的评论。
Check out a thorough treatment from @T.J. Crowder's blog, as posted in his comment below.
这篇关于检查对象数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!