js 對象及空對象或數組及空數組的判斷與比較


 工作中經常會使用到,這里記錄一下

判斷是不是對象: let obj = {}; Object.prototype.toString.call(obj) == "[object Object]";  //true
 判斷是不是數組: let array = []; Object.prototype.toString.call(array) == "[object Array]";  //true
 判斷是不是字符串: let str = ''; Object.prototype.toString.call(str) == "[object String]";  //true
 判斷是不是數字: let num = 1; Object.prototype.toString.call(num) == "[object Number]";    //true
 判斷是不是布爾: let boolean = false; Object.prototype.toString.call(boolean) == "[object Boolean]";  //true
 判斷是否有效: let data; Object.prototype.toString.call(data) != "[object Null]" && Object.prototype.toString.call(data) != "[object Undefined]";  //false

 

 
判斷數組是否為空:
let arr = [];
arr.length == 0;  //true
var aa = ['','','','']
aa.join('') === '';//true

 

 
對象轉數組:
let obj = {1: 'a', 2: 'b', 3:'c'}
Object.keys(obj);  //[1, 2, 3]
Object.values(obj);  //['a', 'b', 'c']
 

判斷對象是否為空:

let obj = {}

Object.keys(obj).length == 0  //true
var abc = {1:'',2:'',3:''}
Object.values(abc).join('') !== '';//true

 

比較2個數組是否相等(忽略每項的類型)
let arr1 = ["1",2];
let arr2 = [1,2];
arr1.toString() == arr2.toString();  //true
 
 
 
 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM