Json数组返回null
问题描述:
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>
答
您正在尝试为对象的每个元素分配一些值。问题是,你试图像数组那样对待那个对象,认为JS会神奇地理解你想要做什么。它不会。
一种可能的方式其实就是做你想做的:
for (var i in abc) if (abc.hasOwnProperty(i)) {
abc[i] = "1";
}
这样a
,b
,abc
对象的c
属性将得到 “1” 值。现在,您更改0
,1
,2
属性(是的,这些属性是JS中的对象属性的有效名称;但是它们在数组中使用得更多)。
是什么让你觉得'abc [0] =“1”'与'abc.a =“1”相同? – dotnetom 2014-11-23 09:31:16
请不要将报价格式用于不是报价的东西。 – JJJ 2014-11-23 09:35:54
'for'循环可能如何工作 - 它生成一个数组。您发回控制器接受对象的方法,而不是集合! – 2014-11-23 10:02:28