JS Null 空 判斷


 

JS判斷對象是否為空

https://www.cnblogs.com/mountain-mist/articles/1600995.html
http://www.cftea.com/c/2007/04/YK4PY29JW82CZOVY.asp

 

 

JS如何判斷一個數組是否為空、是否含有某個值? 下面的方法不能判斷對象是否為 0、null、undefined 1.js判斷數組是否為空?

let arr = [];
if (arr.length == 0){
   console.log("數組為空")
}else {
   console.log("數組不為空")
}

2. js判斷數組是否含有某個值?
方法一:  arr.indexOf()
if (arr.indexOf(2) != -1){
   console.log("數組含有2")
}else {
   console.log("數組不含2")
}

方法二:  for循環結合if判斷
for (let i = 0;i < arr.length;i++){
   if (arr[i] === 2){
      console.log("數組含有2")
  }
}

方法三: arr.find(callback)   
arr.find(value => {
   if (value === 2){
      console.log("數組含有2")
  }
})

方法四: arr.includes()   數組中含有某值返回true,沒有返回false。ES7新方法。

let arr = [1,2,3,4];
if(arr.includes(2)){
  console.log("數組中有2");
}else{
  console.log("數組中無2");
}

 


免責聲明!

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



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