mpe*_*pen 2581 javascript arrays javascript-objects
我正在尝试编写一个接受字符串列表或单个字符串的函数.如果它是一个字符串,那么我想将它转换为只有一个项目的数组.然后我可以循环它而不用担心错误.
那么我该如何检查变量是否是一个数组?
我已经完成了下面的各种解决方案,并创建了一个jsperf测试.
use*_*716 1920
ECMAScript标准中给出的用于查找Object类的toString方法是使用该方法Object.prototype.
if( Object.prototype.toString.call( someVar ) === '[object Array]' ) {
alert( 'Array!' );
}
Run Code Online (Sandbox Code Playgroud)
或者你可以typeof用来测试它是否是一个字符串:
if( typeof someVar === 'string' ) {
someVar = [ someVar ];
}
Run Code Online (Sandbox Code Playgroud)
或者如果你不关心性能,你可以只做concat一个新的空数组.
someVar = [].concat( someVar );
Run Code Online (Sandbox Code Playgroud)
还有你可以直接查询的构造函数:
if (somevar.constructor.name == "Array") {
// do something
}
Run Code Online (Sandbox Code Playgroud)
检查出一个彻底的治疗从@TJ克罗德的博客,张贴在他的评论如下.
查看此基准测试以了解哪种方法表现更好:http://jsben.ch/#/QgYAV
从@Bharath转换字符串到使用Es6的数组问题:
const convertStringToArray = (object) => {
return (typeof object === 'string') ? Array(object) : object
}
Run Code Online (Sandbox Code Playgroud)
假设:
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']
Run Code Online (Sandbox Code Playgroud)
Cha*_*ion 1259
我首先检查您的实现是否支持isArray:
if (Array.isArray)
return Array.isArray(v);
Run Code Online (Sandbox Code Playgroud)
您也可以尝试使用该instanceof运算符
v instanceof Array
Run Code Online (Sandbox Code Playgroud)
Fel*_*len 809
在现代浏览器中,您可以做到
Array.isArray(obj)
Run Code Online (Sandbox Code Playgroud)
(受 Chrome 5,Firefox 4.0,IE 9,Opera 10.5和Safari 5支持)
为了向后兼容,您可以添加以下内容
# only implement if no native implementation is available
if (typeof Array.isArray === 'undefined') {
Array.isArray = function(obj) {
return Object.prototype.toString.call(obj) === '[object Array]';
}
};
Run Code Online (Sandbox Code Playgroud)
如果你使用jQuery,你可以使用jQuery.isArray(obj)或$.isArray(obj).如果你使用下划线,你可以使用_.isArray(obj)
如果您不需要检测在不同帧中创建的阵列,您也可以使用 instanceof
obj instanceof Array
Run Code Online (Sandbox Code Playgroud)
jan*_*anr 295
jQuery还提供了一种$.isArray()方法:
var a = ["A", "AA", "AAA"];
if($.isArray(a)) {
alert("a is an array!");
} else {
alert("a is not an array!");
}Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>Run Code Online (Sandbox Code Playgroud)
shi*_*obi 102
这是所有方法中最快的(支持所有浏览器):
function isArray(obj){
return !!obj && obj.constructor === Array;
}
Run Code Online (Sandbox Code Playgroud)
Ali*_*eza 45
想象一下,你有这个数组如下:
var arr = [1,2,3,4,5];
Run Code Online (Sandbox Code Playgroud)
Javascript(新旧浏览器):
function isArray(arr) {
return arr.constructor.toString().indexOf("Array") > -1;
}
Run Code Online (Sandbox Code Playgroud)
要么
function isArray(arr) {
return arr instanceof Array;
}
Run Code Online (Sandbox Code Playgroud)
要么
function isArray(arr) {
return Object.prototype.toString.call(arr) === '[object Array]';
}
Run Code Online (Sandbox Code Playgroud)
然后像这样称呼它:
isArray(arr);
Run Code Online (Sandbox Code Playgroud)
Javascript(IE9 +,Ch5 +,FF4 +,Saf5 +,Opera10.5 +)
Array.isArray(arr);
Run Code Online (Sandbox Code Playgroud)
jQuery的:
$.isArray(arr);
Run Code Online (Sandbox Code Playgroud)
角度:
angular.isArray(arr);
Run Code Online (Sandbox Code Playgroud)
下划线和Lodash:
_.isArray(arr);
Run Code Online (Sandbox Code Playgroud)
Cru*_*ult 33
Array.isArray运行速度很快,但并不是所有版本的浏览器都支持它.所以你可以为其他人做一个例外并使用通用方法:
Utils = {};
Utils.isArray = ('isArray' in Array) ?
Array.isArray :
function (value) {
return Object.prototype.toString.call(value) === '[object Array]';
}
Run Code Online (Sandbox Code Playgroud)
小智 23
简单的功能来检查这个:
function isArray(object)
{
if (object.constructor === Array) return true;
else return false;
}
Run Code Online (Sandbox Code Playgroud)
Vik*_*mar 16
这个问题只有一个解决方案
x instanceof Array
Run Code Online (Sandbox Code Playgroud)
其中x是变量,如果x是数组,它将返回true,如果不是则返回false.
Bil*_*oon 14
我会创建一个函数来测试你正在处理的对象的类型......
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 StringRun Code Online (Sandbox Code Playgroud)
然后你可以写一个简单的if语句......
if(whatAmI(myVar) === "Array"){
// do array stuff
} else { // could also check `if(whatAmI(myVar) === "String")` here to be sure
// do string stuff
}
Run Code Online (Sandbox Code Playgroud)
Ahm*_*DAL 14
您可以检查变量的类型是否为数组;
var myArray=[];
if(myArray instanceof Array)
{
....
}
Run Code Online (Sandbox Code Playgroud)
Geo*_*pty 11
考虑到这些意见,我试图改进这个答案:
var isArray = myArray && myArray.constructor === Array;
Run Code Online (Sandbox Code Playgroud)
它摆脱了if/else,并解释了数组为null或未定义的可能性
小智 11
我这样做的方式非常简单.适合我.有什么缺点吗?
Array.prototype.isArray = true;
a=[]; b={};
a.isArray // true
b.isArray // (undefined -> false)
Run Code Online (Sandbox Code Playgroud)
Saf*_*eli 10
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/isArray
Array.isArray = Array.isArray || function (vArg) {
return Object.prototype.toString.call(vArg) === "[object Array]";
};
Run Code Online (Sandbox Code Playgroud)
小智 10
我用两种替代方法更新了jsperf小提琴以及错误检查.
事实证明,在'Object'和'Array'原型中定义常量值的方法比任何其他方法都快.这是一个有点令人惊讶的结果.
/* Initialisation */
Object.prototype.isArray = function() {
return false;
};
Array.prototype.isArray = function() {
return true;
};
Object.prototype._isArray = false;
Array.prototype._isArray = true;
var arr = ["1", "2"];
var noarr = "1";
/* Method 1 (function) */
if (arr.isArray()) document.write("arr is an array according to function<br/>");
if (!noarr.isArray()) document.write("noarr is not an array according to function<br/>");
/* Method 2 (value) - **** FASTEST ***** */
if (arr._isArray) document.write("arr is an array according to member value<br/>");
if (!noarr._isArray) document.write("noarr is not an array according to member value<br/>");Run Code Online (Sandbox Code Playgroud)
如果变量采用未定义的值,则这两种方法不起作用,但如果您确定它们具有值,则它们可以正常工作.关于如果值是数组或单个值而考虑性能,第二种方法看起来像一个有效的快速方法.它比Chrome上的'instanceof'略快,是Internet Explorer,Opera和Safari(在我的机器上)中第二好的方法的两倍.
我知道,人们正在寻找某种原始的javascript方法.但如果你想减少思考,请看看这里:http://underscorejs.org/#isArray
_.isArray(object)
Run Code Online (Sandbox Code Playgroud)
如果object是Array,则返回true.
(function(){ return _.isArray(arguments); })();
=> false
_.isArray([1,2,3]);
=> true
Run Code Online (Sandbox Code Playgroud)
最好的做法是比较它使用 constructor ,像这样
if(some_variable.constructor === Array){
// do something
}
Run Code Online (Sandbox Code Playgroud)
您也可以使用其他方法,例如typeOf,将其转换为字符串然后进行比较,但将其与 dataType 进行比较总是更好的方法。
如果可以传递给此函数的仅有两种值是字符串或字符串数组,请保持简单并typeof检查字符串的可能性:
function someFunc(arg) {
var arr = (typeof arg == "string") ? [arg] : arg;
}
Run Code Online (Sandbox Code Playgroud)
我见过的最好的解决方案是替换typeof的跨浏览器.在这里查看Angus Croll的解决方案.
TL; DR版本如下,但文章是对该问题的一个很好的讨论,所以如果你有时间你应该阅读它.
Object.toType = function(obj) {
return ({}).toString.call(obj).match(/\s([a-z|A-Z]+)/)[1].toLowerCase();
}
// ... and usage:
Object.toType([1,2,3]); //"array" (all browsers)
// or to test...
var shouldBeAnArray = [1,2,3];
if(Object.toType(shouldBeAnArray) === 'array'){/* do stuff */};
Run Code Online (Sandbox Code Playgroud)
这是我的懒惰方法:
if (Array.prototype.array_ === undefined) {
Array.prototype.array_ = true;
}
// ...
var test = [],
wat = {};
console.log(test.array_ === true); // true
console.log(wat.array_ === true); // false
Run Code Online (Sandbox Code Playgroud)
我知道"混乱"原型是一种亵渎,但它似乎比推荐的toString方法表现得更好.
注意:这种方法的一个缺陷是它不会跨越iframe边界,但对于我的用例,这不是问题.
Stoyan Stefanov的书籍JavaScript Patterns中有一个很好的例子,它假设处理所有可能的问题以及利用ECMAScript 5方法Array.isArray().
所以这里是:
if (typeof Array.isArray === "undefined") {
Array.isArray = function (arg) {
return Object.prototype.toString.call(arg) === "[object Array]";
};
}
Run Code Online (Sandbox Code Playgroud)
顺便说一句,如果你使用jQuery,你可以使用它的方法$ .isArray()
如果您知道对象没有concat方法,则可以使用以下代码.
var arr = [];
if (typeof arr.concat === 'function') {
console.log("It's an array");
}Run Code Online (Sandbox Code Playgroud)
这个函数几乎可以把任何东西都变成一个数组:
function arr(x) {
if(x === null || x === undefined) {
return [];
}
if(Array.isArray(x)) {
return x;
}
if(isString(x) || isNumber(x)) {
return [x];
}
if(x[Symbol.iterator] !== undefined || x.length !== undefined) {
return Array.from(x);
}
return [x];
}
function isString(x) {
return Object.prototype.toString.call(x) === "[object String]"
}
function isNumber(x) {
return Object.prototype.toString.call(x) === "[object Number]"
}
Run Code Online (Sandbox Code Playgroud)
它使用了一些较新的浏览器功能,因此您可能需要对其进行 polyfill 以获得最大支持。
例子:
> arr(null);
[]
> arr(undefined)
[]
> arr(3.14)
[ 3.14 ]
> arr(1/0)
[ Infinity ]
> gen = function*() { yield 1; yield 2; yield 3; }
[Function: gen]
> arr(gen())
[ 1, 2, 3 ]
> arr([4,5,6])
[ 4, 5, 6 ]
> arr("foo")
[ 'foo' ]
Run Code Online (Sandbox Code Playgroud)
NB 字符串将被转换为具有单个元素的数组而不是字符数组。isString如果您希望相反,请删除检查。
我在Array.isArray这里使用它是因为它最健壮,也最简单。
检查对象是否为数组的最简单,最快捷的方法.
var arr = [];
arr.constructor.name ==='Array' //return true;
Run Code Online (Sandbox Code Playgroud)
要么
arr.constructor ===Array //return true;
Run Code Online (Sandbox Code Playgroud)
或者你可以做一个实用功能:
function isArray(obj){ return obj && obj.constructor ===Array}
Run Code Online (Sandbox Code Playgroud)
用法:
isArray(arr); //return true
Run Code Online (Sandbox Code Playgroud)
var a = [], b = {};
console.log(a.constructor.name == "Array");
console.log(b.constructor.name == "Object");
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1441729 次 |
| 最近记录: |