2011-01-12 5 views
4

난 그냥 다른 개발자에서 프로젝트를 인수했고 코드를 많이 가지고보다 큰 값을 확인하는 좋은 방법이 공백 또는 널 (null)이없는 것입니다 같은 if 문 :

if(value != null || value != "" || value != undefined) 
{ 
    doSomeThing(); 
} 

어떤 ok, 약간의 어지러워하는 것은 도처에 사용했을 때 얻는다. 이것을 작성하는 더 좋은, 깔끔한 방법이 있습니까? 나는 이것을 생각하고 있었다.

if(value.length > 0 || value != undefined) 
{ 
    doSomeThing(); 
} 

당신은 모두 무엇을 생각하니?

감사

스티븐

답변

9

값이 nullvalue.length는 런타임 오류 형식 오류 thhrow 것이다 때 거의,하지만와 if(value.length > 0 || value != undefined)을 : 당신이 null 값 속성에 액세스하려고 같은 오류 # 1009.

if (value!=null&&value.length>0) {doSomeThing();}

이하 다른 형태 :

if ((value||"").length>0) {doSomeThing();} 

한 참고 : 값의 입력하지 않으면

은 그래서 당신은 값이 예를 들어 비 널 (null)이 그 전에 확인해야 * 인 경우 값을 정의 할 수 없으므로 null이됩니다.

var str:String=undefined; 
trace(str==null); // will output true 
+0

감사합니다. 패트릭 감사합니다.이 두 옵션은 더 깨끗하게 보입니다. 또한 값 유형이 설정되어있는 경우 알지 못했습니다. String는 null을 반환하고 정의되지 않은 문자열을 반환합니다. AS3에서 뭔가 새로운 것인가? undefined로 작업 한 AS2 코드 중 일부는 항상 확인 했습니까? – StephenAdams

3

나는 더 긍정적 인 말을 쓰기를 좋아합니다. 프로그래머의 진술은 무언가가 null이 아닌인지 확인하지만 그는 의미한다. 존재하는 경우 : 배열이나 문자열의 경우

을 나는 이것을 사용이 존재하는 경우

if (value && value.length > 0) doSomething(); 

그러나 개체 또는 내가 이것을 사용 DisplayObject의 경우

확인 할 수 있습니다.

if (mc) doSomething(); 

대부분의 경우 충분합니다.

3

다음은 재생할 수있는 타임 라인 코드입니다.

import flash.display.MovieClip; 
import flash.display.Sprite; 

var object : Object; 
var array : Array; 
var number : Number; 
var integer : int; 
var uinteger : uint; 
var string : String; 
var xml : XML; 
var regexp : RegExp; 
var movieClip : MovieClip; 
var array2 : Array = []; 
var object2 : Object = {}; 

trace("uninstantiated Object =", object, "Boolean cast =", Boolean(object)); 
trace("uninstantiated Array =", array, "Boolean cast =", Boolean(array)); 
trace("uninstantiated Number =", number, "Boolean cast =", Boolean(number)); 
trace("uninstantiated int =", integer, "Boolean cast =", Boolean(integer)); 
trace("uninstantiated uint =", uinteger, "Boolean cast =", Boolean(uinteger)); 
trace("uninstantiated String =", string, "Boolean cast =", Boolean(string)); 
trace("empty String =", "", "Boolean cast =", Boolean("")); 
trace("uninstantiated XML =", xml, "Boolean cast =", Boolean(xml)); 
trace("uninstantiated RegExp =", regexp, "Boolean cast =", Boolean(regexp)); 
trace("uninstantiated MoveClip =", movieClip, "Boolean cast =", Boolean(movieClip)); 
trace("instantiated Array with length 0 XML =", array2, "Boolean cast =", Boolean(array2)); 
trace("instantiated Object with no properties =", object2, "Boolean cast =", Boolean(object2)); 
trace("uninstantiated index of instantiated array =", array2[4], "Boolean cast =", Boolean(array2[4])); 
trace("uninstantiated property of instantiated object =", object2[ "color" ], "Boolean cast =", Boolean(object2[ "color" ])); 
try 
{ 
//will throw an error 
trace("uninstantiated property of uninstatinated class =", movieClip.x, "Boolean cast =", Boolean(movieClip.x)); 
} 
catch (e : Error) {} 

/* 
output: 

uninstantiated Object = null Boolean cast = false 
uninstantiated Array = null Boolean cast = false 
uninstantiated Number = NaN Boolean cast = false 
uninstantiated int = 0 Boolean cast = false 
uninstantiated uint = 0 Boolean cast = false 
uninstantiated String = null Boolean cast = false 
empty String = Boolean cast = false 
uninstantiated XML = null Boolean cast = false 
uninstantiated RegExp = null Boolean cast = false 
uninstantiated MoveClip = null Boolean cast = false 
instantiated Array with length 0 XML = Boolean cast = true 
instantiated Object with no properties = [object Object] Boolean cast = true 
uninstantiated index of instantiated array = undefined Boolean cast = false 
uninstantiated property of instantiated object = undefined Boolean cast = false 

As you can see, in general, you can just test for instantiation by using 
if (variableName) ... 

But this will fail if you want to think of instantiated-but-empty Arrays and Objects 
as false. Note that it will also fail, generating an error, if you check for properies 
of uninitialized classes, e.g. 

var sprite : Sprite; 
if (sprite.x) trace("found x"); //error, because sprite = null and null doesn't have an x property. 

You can write a more liberal test like this: 
*/ 

function exists(value : *) : Boolean 
{ 
    var result : Boolean = true; 
    if (! value) return false; 
    if (value is Array && ! value.length) return false; 
    if (value.constructor.toString() == "[class Object]") 
    { 
     result = false; 
     for each (var prop in value) { result = true; break; } 
    } 

    return result; 
} 

//tests 

trace("exists(object) =", exists(object)); 
trace("exists(array) =", exists(array)); 
trace("exists(number) =", exists(number)); 
trace("exists(integer) =", exists(integer)); 
trace("exists(uinteger) =", exists(uinteger)); 
trace("exists(string) =", exists(string)); 
trace("exists('') =", exists("")); 
trace("exists(xml) =", exists(xml)); 
trace("exists(regexp) =", exists(regexp)); 
trace("exists(movieClip) =", exists(movieClip)); 
trace("exists(array2) =", exists(array2)); 
trace("exists(object2) =", exists(object2)); 
trace("exists(array2[4]) =", exists(array2[4])); 
trace("exists(object2[ 'color' ]) =", exists(object2[ "color" ])); 

var sprite : Sprite = new Sprite(); 
trace("INSTANTIATED: exists(sprite) = ", exists(sprite)); 

var object3 : Object = { color : 0xFFFFFF }; 
trace("INSTANTIATED OBJECT WITH PROPERTY: exists(object3) =", exists(object3)); 

var array3 : Object = [ 1 ]; 
trace("INSTANTIATED ARRAY WITH LENGTH: exists(array3) =", exists(array3)); 

/* 
output: 

exists(object) = false 
exists(array) = false 
exists(number) = false 
exists(integer) = false 
exists(uinteger) = false 
exists(string) = false 
exists('') = false 
exists(xml) = false 
exists(regexp) = false 
exists(movieClip) = false 
exists(array2) = false 
exists(object2) = false 
exists(array2[4]) = false 
exists(object2[ 'color' ]) = false 
INSTANTIATED: exists(sprite) = true 
INSTANTIATED OBJECT WITH PROPERTY: exists(object3) = true 
INSTANTIATED ARRAY WITH LENGTH: exists(array3) = true 

One more note: be careful with ints and uints. They are always initialized. Whereas other variables 
point to null, undefined or NaN until you give them values, ints and uints are automatically intialized 
to zero. There is not way to have an int that doesn't point to a value: 

var num : Number; 
var i : int; 
trace(num); // NaN 
trace(i); //0 

In general, that's okay, because 0 == false: 

var i : int; 
if (i) trace("false"); //false 

But I've mixed myself up before with code like this: 

var color : int = getColorValueFromXML(); 
if (color) drawCircleWithColor(color); 

In the above code, I only want to draw a circle if color is initialized. 
However, color will ALWAYS bee initialized, to zero if not to anything else. 

But what if getColorValueFromXML() returns 0x00000. We think of that as the 
color black. But I see a black circle, because 0x000000 is also the same 
as 0. And, in a conditional, 0 parses as false: 

if (0x000000) drawCircleWithColor(); //drawCircleWithColor won't run! 
*/