2014-11-23 101 views
-2

for循環中的數組返回null。Json數組返回null

當我這樣做:

abc.a = "1"; 
abc.b = "1"; 
abc.c = "1"; 

這一切都很好。 但這返回null:

for (var i = 0; i < 3; i++) { 
    abc[i] = "1";    
} 

控制器的MVC框架:

public class abcController : Controller 
{ 

    public ActionResult Index() 
    { 
    return View(); 
    } 

    [HttpPost] 
    public ActionResult Index(abc val) 
    { 
    return View(); 
    } 
} 

MODEL MVC abcCLASS:

public class abc 
{ 
    public string a {get;set;} 
    public string b { get; set; } 
    public string c { get; set; } 
} 

HTML + jQuery的

我想的是,對於意志也工作。

爲什麼在for循環中對象返回null?

<input type="button" id="bbb"/> 

<script> 
    var abc = { a: "", b: "", c: "" }; 
    $("#bbb").click(function() { 
    // This not working: 
    for (var i = 0; i < 3; i++) {  
     abc[i] = "1";    
    } 
    // This working: 
    abc.a = "1"; 
    abc.b = "1"; 
    abc.c = "1"; 

    $.ajax({ 
     url: '/abc/index', 
     type: "POST", 
     dataType: 'json', 
     traditional: true, 
     contentType: 'application/json; charset=utf-8', 
     data: JSON.stringify(abc), 
     success: function (response) { 
     console.log(response); 
     } 
    }); 
    }); 
</script> 
+4

是什麼讓你覺得'abc [0] =「1」'與'abc.a =「1」相同? – dotnetom 2014-11-23 09:31:16

+0

請不要將報價格式用於不是報價的東西。 – JJJ 2014-11-23 09:35:54

+0

'for'循環可能如何工作 - 它生成一個數組。您發回控制器接受對象的方法,而不是集合! – 2014-11-23 10:02:28

回答

0

您正在嘗試爲對象的每個元素分配一些值。問題是,你試圖像數組那樣對待那個對象,認爲JS會神奇地理解你想要做什麼。它不會。

一種可能的方式其實就是做你想做的:

for (var i in abc) if (abc.hasOwnProperty(i)) {  
    abc[i] = "1"; 
} 

這樣ababc對象的c屬性將得到 「1」 值。現在,您更改0,1,2屬性(是的,這些屬性是JS中的對象屬性的有效名稱;但是它們在數組中使用得更多)。

+0

我想只運行數組的一半,我neet我<5'你的例子像它的foreach – david 2014-11-23 10:47:06

+0

你調用數組的哪部分數據? – raina77ow 2014-11-23 12:34:29