Aad*_*adi 5 javascript jquery html5 json jquery-mobile
这是我的json
{
"data": [
[
"1",
"Skylar Melovia"
],
[
"4",
"Mathew Johnson"
]
]
}
Run Code Online (Sandbox Code Playgroud)
this is my code jquery Code
for(i=0; i<= contacts.data.length; i++) {
$.each(contacts.data[i], function( index, objValue ){
alert("id "+objValue);
});
}
Run Code Online (Sandbox Code Playgroud)
我得到了我的数据,objValue但我想分别存储在数组中id,name看起来我的代码看起来如下
var id=[];
var name = [];
for(i=0; i<= contacts.data.length; i++){
$.each(contacts.data[i], function( index, objValue ) {
id.push(objValue[index]); // This will be the value "1" from above JSON
name.push(objValue[index]); // This will be the value "Skylar Melovia" from above JSON
});
}
Run Code Online (Sandbox Code Playgroud)
我怎样才能做到这一点.
$.each(contacts.data, function( index, objValue )
{
id.push(objValue[0]); // This will be the value "1" from above JSON
name.push(objValue[1]); // This will be the value "Skylar Melovia" from above JSON
});
Run Code Online (Sandbox Code Playgroud)
编辑,替代用法:
$.each(contacts.data, function()
{
id.push(this[0]); // This will be the value "1" from above JSON
name.push(this[1]); // This will be the value "Skylar Melovia" from above JSON
});
Run Code Online (Sandbox Code Playgroud)
$.each 将迭代contacts.data,即:
[
//index 1
[
"1",
"Skylar Melovia"
],
//index=2
[
"4",
"Mathew Johnson"
]
]
Run Code Online (Sandbox Code Playgroud)
您通过签名 function(index,Objvalue) 提供的匿名函数将应用于每个元素及其index在 contact.data 数组中的索引及其objValue值。对于索引=1,你将有:
objValue=[
"1",
"Skylar Melovia"
]
Run Code Online (Sandbox Code Playgroud)
然后就可以访问objValue[0]和objValue[1]。
编辑(响应 Dutchie432 评论和回答;)):没有 jQuery 的更快方法, $.each 更容易编写和阅读,但在这里您使用普通的旧 JS :
for(i=0; i<contacts.data.length; i++){
ids.push(contacts.data[i][0];
name.push(contacts.data[i][1];
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4519 次 |
| 最近记录: |