2013-11-26 20 views
2
 json= new Gson().toJson(name); 

其中name是字符串類型。TypeError:無效'in'操作數目標

我得到錯誤說:

錯誤是在Java腳本的給定部分

return type === "array" || type !== "function" && 
    (length === 0 || 
    typeof length === "number" && length > 0 && (length - 1) in obj); 

我也曾嘗試

response=JSON.parse(response); 

「類型錯誤 '在' 操作數OBJ無效」這不起作用。

+0

是什麼'responseJson' –

+0

是什麼'obj'? – Grundy

+0

我從servlet獲取的響應對象 – user2814799

回答

2

通過鏈接In operator可以看到

The in operator returns true if the specified property is in the specified object.

在你的代碼

(length - 1) in obj你嘗試檢查該屬性(length - 1)該數字在你的obj

我覺得objstring,因此它具有length財產,但沒有數字屬性,所以你必須趕上這種情況

+0

這是許多servlets的常見java腳本,我不能改變那只是數值 – user2814799

+0

所以你可以提供什麼是obj值? – Grundy

+0

那麼?如果你有'var obj = {5:'foo'};'然後'obj'中的5將返回'true'。這個錯誤表明'obj'對'in'來說不是一個有效的操作數。 –

1

我關閉代碼「(長度 - 1)在obj」之間括號括起來。

return type === "array" || type !== "function" && 
    (length === 0 || 
    typeof length === "number" && length > 0 && ((length - 1) in obj)); 

這對我來說很好。

0

在我的情況下,對象是不是空的,但我需要的對象的鍵,例如加雙引號:

obj = {params : "paramsInputPreData"} 

上面會產生一個錯誤,但下面一個是好的:

obj = {"params" : "paramsInputPreData"} 

所以對我所需要的密鑰被引用爲「PARAMS」

希望它可以幫助別人

0

當你有這樣的錯誤,你需要檢查你的變量的類型等等,你總是可以做這樣的事情:

if (typeof x == 'string' || typeof x == 'number') { ... }