JavaScript中应该使用哪种方式进行空比较

时间:2018-08-14 04:28:04

标签: javascript

要检查对象在javascript中是否为空,我见过两种方法,

let obj = {};

选项1

if(obj){ console.log('object exists'); }

选项2

if(!!obj === true){ console.log('object exists'); }

选择一个选项比另一个选项有任何优势吗?首选哪个选项作为标准代码?

5 个答案:

答案 0 :(得分:3)

  

使用简单的 ===

在您的代码中,您没有检查对象是否为null。相反,您的代码只是检查它是否不是Falsy值。请注意,JavaScript中共有6个Falsy值,null是其中之一。详细了解它们here。如果您只想检查变量是否为null,则最好的方法是:

if (obj === null) { 
  console.log("object is null");
} else {
  console.log("object is not null");
}

答案 1 :(得分:2)

如果您只想检查对象是否为空:

if(obj === null) {
...
}

答案 2 :(得分:1)

javascript中的对象始终是真实的,无论其上是否定义了任何属性。

因此

var obj={}
if(obj){
//this block will always be executed.
}

如果要检查对象是否已在当前词法范围内定义,请尝试:

if(typeof(obj) !== 'undefined' && obj !== null){ 
  console.log('object exists'); 
}
else{
  console.log('nope')
}

如果要检查对象是否具有任何属性或它是空对象,请尝试:

if(typeof(obj) !== 'undefined' && obj !== null){ 
  console.log('object exists'); 
}
else{
  if(Object.keys(obj).length){
    //do something
  }
}

答案 3 :(得分:0)

要测试值using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Drawing.Printing; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace fileConversion { public partial class Form1 : Form { private static Font printFont; private static StreamReader streamToPrint; public Form1() { InitializeComponent(); } private void selectFile_Click(object sender, EventArgs e) { if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK) { label1.Text = openFileDialog1.FileName; //text label1 tu pegang file name yang kita select } } private void convertFile_Click(object sender, EventArgs e) { try { DialogResult result = printDialog1.ShowDialog(); if (result == DialogResult.OK) { streamToPrint = new StreamReader(@"" + label1.Text); PrintDocument doc = new PrintDocument(); if (printDialog1.PrinterSettings.PrinterName == "Microsoft Print to PDF") { // force a reasonable filename string filename = Path.GetFileNameWithoutExtension(label1.Text); string directory = Path.GetDirectoryName(label1.Text); doc.PrinterSettings.PrintToFile = true; // confirm the user wants to use that name SaveFileDialog saveFileDialog1 = new SaveFileDialog(); saveFileDialog1.InitialDirectory = directory; saveFileDialog1.FileName = filename + ".pdf"; saveFileDialog1.Filter = "PDF File|*.pdf"; result = saveFileDialog1.ShowDialog(); if (result != DialogResult.Cancel) doc.PrinterSettings.PrintFileName = saveFileDialog1.FileName; } if (result != DialogResult.Cancel) // in case they canceled the save as dialog { doc.PrintPage += new PrintPageEventHandler(pd_PrintPage); doc.Print(); } } } finally { streamToPrint.Close(); } } private static void pd_PrintPage(object sender, PrintPageEventArgs ev) { float linesPerPage = 0; float yPos = 0; int count = 0; float leftMargin = ev.MarginBounds.Left; float topMargin = ev.MarginBounds.Top; String line = null; // Calculate the number of lines per page. linesPerPage = ev.MarginBounds.Height / printFont.GetHeight(ev.Graphics); // Iterate over the file, printing each line. while (count < linesPerPage && ((line = streamToPrint.ReadLine()) != null)) { yPos = topMargin + (count * printFont.GetHeight(ev.Graphics)); ev.Graphics.DrawString(line, printFont, Brushes.Black, leftMargin, yPos, new StringFormat()); count++; } // If more lines exist, print another page. if (line != null) ev.HasMorePages = true; else ev.HasMorePages = false; } } } 是否为对象数据类型,请尝试

obj

if( obj and typeof obj === "object") { // obj is an object and it's safe to access properties } 的真实性表明它不是obj,而null返回“对象”意味着它不是某种其他原始数据类型。

请注意,typeof是JavaScript中自己的数据类型(空),但是由于该语言的早期实现存在局限性,null返回“对象”。

相反,要测试值是否为typeof null而不是对象,只需使用严格的相等性测试:

null

答案 4 :(得分:-3)

选择比较方法取决于您如何预测数据类型, 但是如果您想要一个真正安全的标准,请使用'typeof'。 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof

if(typeof obj ===“ object”){console.log('对象存在'); }

if(typeof obj!==“ undefined”){console.log('对象存在'); }