2012-12-20 117 views
15

我有一個這樣的對象:檢查對象爲空的JavaScript/jQuery的

ricHistory = { 
    name1: [{ 
    test1: value1, 
    test2: value2, 
    test3: value3 
    }], 
    name2: [{ 
    test1: value1, 
    test2: value2, 
    test3: value3 
    }] 
}; 

現在我要檢查,如果如name2在Javascript/jQuery中爲空。我知道方法hasOwnProperty。它只適用於data.hasOwnProperty('name2'),如果名稱存在與否,但我必須檢查它是否爲空。

+0

你的問題問如何檢查的對象是空的,但你的問題的身體詢問如何檢查數組是空的。請對未來的讀者更具體。 – Jared

+0

[Is object empty?]可能重複(http://stackoverflow.com/questions/4994201/is-object-empty) – sierrasdetandil

回答

6

試試這個:

if (ricHistory.name2 && 
    ricHistory.name2 instanceof Array && 
    !ricHistory.name2.length) { 
    console.log('name2 is empty array'); 
} else { 
    console.log('name2 does not exists or is not an empty array.'); 
} 

上述解決方案將告訴你richHistory.name2是否存在,是一個數組,它不是空的。

+0

爲什麼不把所有三個檢查放在一個大的,如果? –

2

試試這個實用的功能:

function isEmpty(obj) { 
if(isSet(obj)) { 
    if (obj.length && obj.length > 0) { 
     return false; 
    } 

    for (var key in obj) { 
     if (hasOwnProperty.call(obj, key)) { 
      return false; 
     } 
    } 
} 
return true;  
}; 

function isSet(val) { 
if ((val != undefined) && (val != null)){ 
    return true; 
} 
return false; 
}; 
+0

isSet是什麼? –

+0

對不起!:)這是另一個有用的功能:P – stamat

+0

非常感謝'isEmpty'功能 – terales

-2
if (ricHistory.name2 === undefined) { 
    //This is property has not been set (which is not really the same as empty though...) 
} 
56

您可以通過jQuery.isEmptyObject()

檢查做到這一點,看看如果一個對象是空的(不包含屬性)。

jQuery.isEmptyObject(object) 

例子:

function isSet(val) { return ((val != undefined) && (val != null));} 

我覺得它更容易剛剛返回語句的布爾代替:

jQuery.isEmptyObject({}) // true 
jQuery.isEmptyObject({ foo: "bar" }) // false 

from Jquery

0

您可以通過這樣做,而不是縮短isSet交還,然後返回。

+0

這實際上是對此答案的評論http://stackoverflow.com/a/13973962/3810453 – Zanshin13

3

JQuery的另一種語法是你沒有使用Prototype或類似的,你更喜歡使用$而不是jQuery前綴;

$.isEmptyObject(object) 
0

我去喜歡這一切的時候在我的代碼:

假設我控制器返回象下面這樣的東西:

$return['divostar'] = $this->report->get_additional_divostar_report($data); 
$return['success'] = true; 
return response()->json($return); 

jQuery中,我會檢查象下面這樣:

if (jQuery.isEmptyObject(data.divostar)){ 
     html_result = "<p id='report'>No report yet</p>"; 
     $('#no_report_table').html(html_result).fadeIn('fast'); 
} 
0

您也可以使用此object-empty可重用組件來確定obj參考是空的。

例子:

empty([]) // => true 
empty({}) // => true 
empty(1) // => false 
empty('') // => false 
empty('foo') // => true 

它是如何工作的:

function isEmpty(obj: any): boolean { 
    for (const n in obj) if (hasOwnProperty(obj, n) && obj[n]) return false; // eslint-disable-line 
    return true; 
};