可以将其转换为for循环吗? [英] Can this be turned into a for loop?

查看:71
本文介绍了可以将其转换为for循环吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用For循环清理它。什么是最有效的编码方式呢?

I would like to clean this up with a For loop. What would be the most efficient way coding this out?

我正在创建一个搜索表单,该表单通过数据库查找特定的表单条件。我编码的方式仅适用于8个字段。但是搜索表单可能有8个以上。不过,现在,我希望能够映射结果并显示在结果页面中。

I'm creating a search form that looks through a database for the specific form criteria. The way I have it coded would only work for the 8 Fields. But it is possible for the search form to have more then 8. For now though, I'd like to be able to map the results and display in a results page.

这就是我尝试过的。这根本没有用,对任何人都可能毫无意义。

This is what I tried. This did not work at all and probably make no sense to anyone lol.

 var obj =data[0]

$.get("obj", {data: $('select["Fields.DisplayName" + Fields.DataValue]').val()}, 
            function(data){
                $.each(data, function(i, item) {
                    alert(item);
                });
            }
);

此功能用于获取数据并显示我想要的方式。

This works for getting the data and displaying it how I'd like.

var obj = data[0];

document.getElementById("test").innerHTML = 
"<p>"+ obj.Fields[0].DisplayName + ":  " + obj.Fields[0].DataValue + "</p>" +
"<p>" + obj.Fields[1].DisplayName + ":  " + obj.Fields[1].DataValue + "</p>" +  
"<p>"+ obj.Fields[2].DisplayName + ":  " + obj.Fields[2].DataValue + "</p>" +  
"<p>"+ obj.Fields[3].DisplayName + ":  " + obj.Fields[3].DataValue + "</p>" +
"<p>" + obj.Fields[4].DisplayName + ":  " + obj.Fields[4].DataValue + "</p>" +
"<p>" + obj.Fields[5].DisplayName + ":  " + obj.Fields[5].DataValue + "</p>" +  
"<p>"+ obj.Fields[6].DisplayName + ":  " + obj.Fields[6].DataValue + "</p>" +
"<p>" + obj.Fields[7].DisplayName + ":  " + obj.Fields[7].DataValue + "</p>" 
    ;

下一个问题是如果有多个数据对象。目前,我已将其设置为循环遍历第一个对象,但是删除该对象时,我无法读取未定义的'0'属性。

The next problem is if there is more then 1 data object. Currently I have it set to loop through the first object, but when I remove that I get cannot read property of '0' undefined.

推荐答案

使用 Array.map()并加入结果:

var fields = data[0].Fields ;

document.getElementById("test").innerHTML = fields
  .map(function(field) {
    return '<p>' + field.DisplayName + ': ' + field.DataValue + '</p>';
  })
  .join('\n');

这篇关于可以将其转换为for循环吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆