簡體   English   中英

如何處理Javascript空對象?

[英]How to handle Javascript empty object?

我很難過。

這是代碼:

const clientInfoPromise = buildPromiseMethod
clientInfoPromise.then((clients) => {
    console.log('clients ' + JSON.stringify(clients))
    console.log(clients.typeOf)
    console.log(_.keys(clients))

這是輸出:

clients {}
undefined
['undefined']

我希望_.keys(clients)返回一個空數組而不是一個字符串'undefined'的數組。 _.isEmpty(clients) ? [] : _.keys(clients) _.isEmpty(clients) ? [] : _.keys(clients)不起作用,因為_.isEmpty返回false

ClientInfoPromise在這里定義:

static buildPromiseMethod(cids) {
    if (condition) {
        // fetch data
        const data = [data,data1,data2]
        return Promise.resolve(_.zipObject(cids, data));
    } else {
      const clients = _(cids)
        .indexBy()
        .mapValues(() => {
          return undefined; //contains empty data
        })
        .value();
      return Promise.resolve(clients);
    }
  }

cids可以是undefined[][1,2,3] (數字數組)。

執行console.log(clients.typeOf)

要記錄clients類型,請使用console.log(typeof clients)

的console.log(_。鍵(客戶端))
<['undefined']

_.key報告clients有一個名為"undefined"密鑰。 最有可能的是, stringify沒有顯示這個鍵值對,因為它的值也是未定義的,這意味着它將被stringify跳過。

要驗證這一點,而不是

console.log('clients'+ JSON.stringify(clients))

使用

console.log('clients', clients)

這將顯示所有屬性,包括stringify將跳過的屬性,因為它們的值未定義。

在您的特定情況下,您報告的行為最好通過buildPromiseMethod的錯誤來解釋,即它返回的promise將被解析為具有單個鍵“undefined”且具有不可序列化值的對象。例如,請考慮以下內容:

> clients = { undefined: undefined };
> console.log('clients ' + JSON.stringify(clients))
< clients {}

> console.log(_.keys(clients))
< ['undefined']

這正是你得到的。

但是, buildPromiseMethod如何返回這樣一個格式錯誤的對象並不明顯。 最可能的罪魁禍首是zipObject 這真的是您運行的確切源代碼嗎? 例如, _.zipObject([cids], data) (將cids指定為數組,當其值未定義,而data也包含未定義的值)可能導致報告的行為:

var data, data1, data2;       // values are undefined
data = [data, data1, data2];
var cids = undefined;
_.zipObject([cids], data);

> { undefined: undefined }

順便說一句,你使用promises可能是錯誤的,至少假設// fetch data是異步的。 你可能想要

static buildPromiseMethod(cids) {
  if (condition) {
    return fetchdata().then(data => 
      _.zipObject(cids, data));
  }

或類似的東西。 這可能與您的問題有關,如果data1等從promise中返回,並且您在promise完成之前嘗試訪問它,在這種情況下它的值將是未定義的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM