2016-08-03 69 views
0

考慮:爲什麼這個對象的鍵字符串?

request = .ajax({ 
    method: 'POST', 
    data : JSON.stringify(object), 
    url : 'offline_ajax_queue.php', 
    contentType : 'application/json', 
    dataType : 'json', 
    cache : false, 
    success : function(response) { 
     console.log(response); 
     for (var key in response) { 
      if (response.hasOwnProperty(key)) { 
       console.log(key, response[key]); 
       if(response[key] > -1) 
        removeAction(key); 
      } 
     } 
    } 
}); 

,並在控制檯中,響應=

{1: 1, 2: 0, 3: 0, 4: 0} 

和:

typeof response[key] // "number" 

爲什麼是關鍵string,而不是number呢?

typeof key // "string" 
+2

因爲他們總是。對象屬性是根據定義的字符串。 –

+1

對象鍵是字符串。即使是數組索引。 – undefined

回答

5

對象屬性名稱總是字符串或符號,從未數字。

(A Map可以具有不同數據類型的密鑰)。

+0

是的,它是一個單獨的但相關的問題:那麼爲什麼它們在輸出中看起來像一個「數字」? – David

+1

@David由於控制檯試圖顯示人性化的輸出。 – undefined

+1

@David,你的意思是控制檯的輸出?這只是瀏覽器格式輸出。如果您將它轉換爲JSON,您會看到它被引號包裝爲一個字符串:'JSON.stringify({1:1})'將會是'{「1」:1}' –

相關問題