10 ways how js determines the data type of a variable is an array All In One
10 ways how js determines the data type of a variable is an array All In One
js 如何判断一个变量的数据类型是数组的 10 种方式 All In One
typeof bug
typeof undefined
typeof null
// 'object'
typeof []
// 'object'
const func = (...args) => console.log(args);
typeof func;
// 'function'
Primitive Data types:
Number, String, Boolean, Undefined, Null , Symbol, BigInt
Non-Primitive data types:
Object
Array
Function ?
solutions
Array.isArray
✅
const arr = [];
Array.isArray(arr);
// true
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray
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
Object.prototype.toString
const arr = [];
Object.prototype.toString.call(arr)
// '[object Array]'
Object.prototype.toString.call(null);
'[object Null]'
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
JSON.stringify
👎
// 仅适用空数组 ⚠️
const arr = [];
JSON.stringify(arr) === JSON.stringify([]);
// true
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify
- regular expression
RegExp
// 字符串正则匹配 `[*]`,
const arr = [1,2,3];
JSON.stringify(arr);
// '[1,2,3]'
const str = JSON.stringify(arr);
const reg = /^\[(.)*\]$/ig;
reg.test(str);
// true
reg.exec(str);
// null ❌ ??? why
// `g` flag bug ✅ https://www.cnblogs.com/xgqfrms/p/16808348.html#5114470
$
fix bug
- reg = /^\[(.)+$\]/;
- reg = /^\[(\w)+$\]/;
// `^` 位置在最前面
// `$` 位置在最后面 ✅
+ reg = /^\[(.)+\]$/;
+ reg = /^\[(\w)+\]$/;
arr = [1,2,3];
str = JSON.stringify(arr);
reg = /^\[(.)*\]$/;
reg.test(str);
// true
reg.exec(str);
// (2) ['[1,2,3]', '3', index: 0, input: '[1,2,3]', groups: undefined]
//`.` ✅ any character
arr = [1,2,3];
str = JSON.stringify(arr);
reg = /^\[(\w)+\]$/;
reg.test(str);
// false
reg.exec(str);
// null
// The `\w` metacharacter matches word characters.
// A word character is a character `a-z, A-Z, 0-9`, including `_` (underscore).
Special characters in regular expressions.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions/Character_Classes
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions/Quantifiers
Online Regex tester and visualizer
https://extendsclass.com/regex-tester.html
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp
https://regexper.com/#%2F%5E%5C%5B%28.%29*%24%5C%5D%2Fig
https://regexper.com/#%2F%5E%5C%5B%28.%29*%5C%5D%24%2Fig
✅
constructor
&prototype
const arr = [1,2,3];
console.log(arr.constructor === Array);
// true
arr.constructor === Array
// true
arr.constructor === Object;
// false
arr.constructor.prototype === Array.prototype;
// true ✅
arr.constructor.prototype === Object.prototype;
// false ❌
Object, Function, prototype, constructor
https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects/Object_prototypes
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/prototype
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/Object
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/constructor
Object.prototype.isPrototypeOf
=>Array.prototype.isPrototypeOf
原型链
prototype
const arr = [1,2,3];
Array.prototype.isPrototypeOf(arr)
// true ✅
Object.prototype.isPrototypeOf(arr);
// true ⚠️
console.log(Array.prototype.isPrototypeOf(arr));
// true
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array
Object.getPrototypeOf
const arr = [1,2,3];
Object.getPrototypeOf(arr) === Array.prototype;
// true ✅
Object.getPrototypeOf(arr) === Object.prototype;
// false ❌
console.log(Object.getPrototypeOf(arr) === Array.prototype);
// true
Object.getPrototypeOf(arr);
// [constructor: ƒ, at: ƒ, concat: ƒ, copyWithin: ƒ, fill: ƒ, …]
Array.prototype;
// [constructor: ƒ, at: ƒ, concat: ƒ, copyWithin: ƒ, fill: ƒ, …]
Object.prototype;
// {constructor: ƒ, __defineGetter__: ƒ, __defineSetter__: ƒ, hasOwnProperty: ƒ, __lookupGetter__: ƒ, …}
Array;
// ƒ Array() { [native code] }
Object;
// ƒ Object() { [native code] }
const ObjPrototype = {};
const obj1 = Object.create(ObjPrototype);
console.log(Object.getPrototypeOf(obj1) === ObjPrototype);
// true
const obj2 = Object.create({});
console.log(Object.getPrototypeOf(obj2) === Object);
// false
console.log(Object.getPrototypeOf(obj2) === Object.prototype);
// false
const obj3 = new Object({});
console.log(Object.getPrototypeOf(obj3) === Object.prototype);
// true
toString
&typeof
const arr = [1,2,3];
arr.toString()
// '1,2,3'
typeof arr;
// 'object'
console.log(arr.toString() !== "[object Object]" && typeof arr === "object");
// true
const obj = {};
console.log(obj.toString());
// "[object Object]"
const arr = [1,2,3];
console.log(arr.toString());
// "1,2,3"
console.log([].toString());
// ""
const func = (...args) => console.log(`args =`, args);
console.log(func.toString());
// "(...args) => console.log(`args =`, args)"
console.log(typeof obj);
console.log(typeof arr);
console.log(typeof func);
// "object"
// "object"
// "function"
- ~ n. js
Array
methods (Feature detection)
数组专有方法的特征检测
const arr = [1,2,3];
arr.slice;
// ƒ slice() { [native code] }
const obj = {};
obj.slice;
// undefined
console.log(arr.slice && typeof arr === "object");
// true
console.log(obj.slice && typeof obj === "object");
// undefined
console.log(!!arr.slice && typeof arr === "object");
// true
console.log(!!obj.slice && typeof obj === "object");
// false
const func = (...args) => console.log(args);
func.slice;
// undefined
Array Methods
Array.prototype[@@iterator]()
Array.prototype.at()
Array.prototype.concat()
Array.prototype.copyWithin()
Array.prototype.entries()
Array.prototype.every()
Array.prototype.fill()
Array.prototype.filter()
Array.prototype.find()
Array.prototype.findIndex()
Array.prototype.findLast()
Array.prototype.findLastIndex()
Array.prototype.flat()
Array.prototype.flatMap()
Array.prototype.forEach()
Array.from()
Experimental
Array.prototype.group()
Experimental
Array.prototype.groupToMap()
Array.prototype.includes()
Array.prototype.indexOf()
Array.isArray()
Array.prototype.join()
Array.prototype.keys()
Array.prototype.lastIndexOf()
Array.prototype.map()
Array.of()
Array.prototype.pop()
Array.prototype.push()
Array.prototype.reduce()
Array.prototype.reduceRight()
Array.prototype.reverse()
Array.prototype.shift()
Array.prototype.slice()
Array.prototype.some()
Array.prototype.sort()
Array.prototype.splice()
Array.prototype.toLocaleString()
Array.prototype.toString()
Array.prototype.unshift()
Array.prototype.values()Methods
Array.prototype[@@iterator]()
Array.prototype.at()
Array.prototype.concat()
Array.prototype.copyWithin()
Array.prototype.entries()
Array.prototype.every()
Array.prototype.fill()
Array.prototype.filter()
Array.prototype.find()
Array.prototype.findIndex()
Array.prototype.findLast()
Array.prototype.findLastIndex()
Array.prototype.flat()
Array.prototype.flatMap()
Array.prototype.forEach()
Array.from()
Experimental
Array.prototype.group()
Experimental
Array.prototype.groupToMap()
Array.prototype.includes()
Array.prototype.indexOf()
Array.isArray()
Array.prototype.join()
Array.prototype.keys()
Array.prototype.lastIndexOf()
Array.prototype.map()
Array.of()
Array.prototype.pop()
Array.prototype.push()
Array.prototype.reduce()
Array.prototype.reduceRight()
Array.prototype.reverse()
Array.prototype.shift()
Array.prototype.slice()
Array.prototype.some()
Array.prototype.sort()
Array.prototype.splice()
Array.prototype.toLocaleString()
Array.prototype.toString()
Array.prototype.unshift()
Array.prototype.values()
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array
RegExp bug
const arr = [1,2,3];
const str = JSON.stringify(arr);
const reg = /^\[(.)*\]$/g;
console.log(`reg = ${reg.test(str)}`);
console.log(`reg = ${reg.exec(str)}`);
// reg = true
// reg = null
const regex = RegExp('^\[(.)*\]$', 'g');
console.log(`regex = ${regex.test(str)}`);
console.log(`regex = ${regex.exec(str)}`);
// regex = false
// regex = null
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/exec
bug fix ✅
https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/RegExp/test
// 字符串正则匹配 `[*]`,
const arr = [1,2,3];
const str = JSON.stringify(arr);
const reg = /^\[(.)*\]$/ig;
console.log(`test with g flag =`, reg.test(str));
// true
console.log(`exec with g flag =`, reg.exec(str));
// null ❌
// test with g flag = true
// exec with g flag = null
console.log(`test with g flag =`, reg.test(str));
// test with g flag = true
console.log(`test with g flag =`, reg.test(str));
// test with g flag = false
// 字符串正则匹配 `[*]`,
const arr = [1,2,3];
const str = JSON.stringify(arr);
const reg = /^\[(.)*\]$/i;
console.log(`test with g flag =`, reg.test(str));
console.log(`exec with g flag =`, reg.exec(str));
// test with g flag = true
// exec with g flag = (2) ['[1,2,3]', '3', index: 0, input: '[1,2,3]', groups: undefined]
console.log(`test with g flag =`, reg.test(str));
console.log(`exec with g flag =`, reg.exec(str));
// test with g flag = true
// exec with g flag = (2) ['[1,2,3]', '3', index: 0, input: '[1,2,3]', groups: undefined]
refs
https://javascript.info/instanceof
https://stackoverflow.com/questions/2449254/what-is-the-instanceof-operator-in-javascript
©xgqfrms 2012-2020
www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!
原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!
本文首发于博客园,作者:xgqfrms,原文链接:https://www.cnblogs.com/xgqfrms/p/16808348.html
未经授权禁止转载,违者必究!