当前位置: 动力学知识库 > 问答 > 编程问答 >

arrays - Javascript treating the number 0 as a blank string?

问题描述:

Noob problem.

In a Google Apps Script, I have an if statement that checks the value of a item in an array, which will either be a number, or blank:

var array = new Array();

array[0] = 1;

if (array[0] == '') {

// this dos not execute

}

array[0] = 0;

if (array[0] == '') {

// this executes

}

The contents of the second if statement get executed because it seems to be treating the 0 as a blank string. When I look at the value of array[0] in the debugger, it shows 0.0 (so it's definitely a number variable).

I first thought to use:

if (array[0] != 0 || array[0] == '')

but I can't use that because the actual if statement is a chain of OR operators like this:

if (array[0] == '' || array[1] == '' || array[2] == '')

and the other values in the array are actually strings, not numbers.

How do I write the if statement so that it differentiates between a 0 number value and no data (blank)?

网友答案:

Use ===

0 == ''  // true
0 === '' // false

Does it matter which equals operator (== vs ===) I use in JavaScript comparisons?

网友答案:

In javascript 0, '', false are called falsy. If you use a == operator on two falsy values - it's always true. Unless you use === operator.

http://www.sitepoint.com/javascript-truthy-falsy/

网友答案:

You can use ===

For Example :

var array = new Array();

array[0] = 0;

if (array[0] === '') { // this doesn't execute }

if (array[0] == '') { // this executes }

分享给朋友:
您可能感兴趣的文章:
随机阅读: