首页 > 其他分享 >6 ways how js determines the data type of a variable is an array All In One

6 ways how js determines the data type of a variable is an array All In One

时间:2022-10-20 01:11:53浏览次数:75  
标签:arr determines ways stringify JSON https const data reg

6 ways how js determines the data type of a variable is an array All In One

js 如何判断一个变量的数据类型是数组的 5 种方式 All In One

typeof bug

typeof undefined

typeof null
// 'object'
typeof []
// 'object'

solutions

  1. Array.isArray
const arr = [];

Array.isArray(arr);
// true

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray

  1. instanceof
// 字面量
const arr = [];
arr instanceof Array;
// true

const arr = new Array();
arr instanceof Array;
// true

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/instanceof

  1. Object.prototype.toString
const arr = [];

Object.prototype.toString.call(arr)
// '[object Array]'


Object.prototype.toString.call(null);
'[object Null]'

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/toString#using_tostring_to_detect_object_class

  1. String.startsWith & String.endsWith
// 字符串匹配开头结尾 `[`& `]`
const arr = [1,2,3];

arr.toString();
// '1,2,3'
`${arr}`;
// '1,2,3'
JSON.stringify(arr);
// '[1,2,3]'

JSON.stringify(arr).startsWith(`[`) && JSON.stringify(arr).endsWith(`]`)
// true

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith

  1. JSON.stringify

    标签:arr,determines,ways,stringify,JSON,https,const,data,reg
    From: https://www.cnblogs.com/xgqfrms/p/16808348.html

相关文章