如何检查对象是否为数组? [英] How to check if an object is an 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, so I can loop over it without fear of an error.
那么如何检查变量是否为数组?
So how do I check if the variable is an array?
我已经整理了以下各种解决方案,并创建了 jsperf测试.它们都很快速,因此只需使用Array.isArray
即可-它是得到良好支持的现在和跨框架工作.
I've rounded up the various solutions below and created a jsperf test. They're all fast, so just use Array.isArray
-- it's well-supported now and works across frames.
推荐答案
ECMAScript标准中提供的用于查找Object类的方法是使用Object.prototype
中的toString
方法.
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
.
Or if you're not concerned about performance, you could just do a concat
to a new empty Array.
someVar = [].concat( someVar );
还有可以直接查询的构造函数:
There's also the constructor which you can query directly:
if (somevar.constructor.name == "Array") {
// do something
}
从
Check out a thorough treatment from @T.J. Crowder's blog, as posted in his comment below.
查看以下基准,以了解哪种方法效果更好:
Check out this benchmark to get an idea which method performs better: http://jsben.ch/#/QgYAV
从 @Bharath 使用Es6将字符串转换为数组,以解决以下问题:
From @Bharath convert string to array using Es6 for the question asked:
const convertStringToArray = (object) => {
return (typeof object === 'string') ? Array(object) : object
}
假设:
let m = 'bla'
let n = ['bla','Meow']
let y = convertStringToArray(m)
let z = convertStringToArray(n)
console.log('check y: '+JSON.stringify(y)) . // check y: ['bla']
console.log('check y: '+JSON.stringify(z)) . // check y: ['bla','Meow']
这篇关于如何检查对象是否为数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!