The method given in the ECMAScript standard to find the class of Object is to use the toString
method from Object.prototype
.(ECMAScript标准中提供的用于找到Object类的方法是使用Object.prototype
的toString
方法。)
if( Object.prototype.toString.call( someVar ) === '[object Array]' ) {
alert( 'Array!' );
}
Or you could use typeof
to test if it is a String:(或者,您可以使用typeof
来测试它是否为字符串:)
if( typeof someVar === 'string' ) {
someVar = [ someVar ];
}
Or if you're not concerned about performance, you could just do a concat
to a new empty Array.(或者,如果你不关心性能,你可以只是做一个concat
到一个新的空数组。)
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 @TJ Crowder's blog, as posted in his comment below.(请查看@TJ Crowder博客的详细处理方法 ,如下面他的评论中所述。)
Check out this benchmark to get an idea which method performs better: http://jsben.ch/#/QgYAV(查看此基准测试 ,以了解哪种方法效果更好: http : //jsben.ch/#/QgYAV)
From @Bharath convert string to array using Es6 for the question asked:(从@Bharath使用Es6将字符串转换为数组以解决以下问题:)
const convertStringToArray = (object) => {
return (typeof object === 'string') ? Array(object) : object
}
suppose:(假设:)
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']
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…