在JavaScript中循环遍历两个数组并构造一个函数

时间:2011-03-30 07:40:03

标签: javascript

我在Javascript中有两个数组,如下所示:

Array one = new Array();
one.push(20061001);
one.push(20061002);
one.push(20061003);
one.push(20061120);


Array two = new Array();
two.push(3.0);
two.push(3.1);
two.push(3.2);
two.push(3.3);

现在有些我需要循环遍历这个数组并构建一个如图所示的函数

function NoisyData() {
return "" + 
"Date,A\n" +
"20061001,3.0\n" +
"20061002,3.1\n" +
"20061003,3.2\n" +
"20061120,4.0\n" ;
}

请帮我解决这个问题?

4 个答案:

答案 0 :(得分:1)

这个怎么样?

var one = new Array();
one.push(20061001);
one.push(20061002);
one.push(20061003);
one.push(20061120);


var two = new Array();
two.push('3.0');
two.push('3.1');
two.push('3.2');
two.push('3.3');



function NoisyData() {

    var result = "Date,A\n";
    for(var i = 0; i < one.length;i++){

        result += one[i] + "," + two[i] + "\n"; 

    }

    return result;

}

alert(NoisyData());

答案 1 :(得分:1)

你的意思是

function NoisyData() {
  var txt = "Date,A\n" 
  for (var i=0, n=one.length;i<n;i++) {
    txt += one[i]+","+two[i]+"\n"
  }
  return txt
}

根据KooiInc's posts更新:

<script>
var one = [20061001,20061002,20061003,20061120]
  , two = [3.0,3.1,3.2,3.3]
  , combined = function(res,two){
       var i = one.length;
       while(i--){
          res[i]+=','+two[i].toPrecision(2);
       }
       res.splice(0,0,'Date,A');
       return res.join('\n')
    }(one.slice(0),two); 
alert(combined);
</script>

而不是one.slice(0)one.clone()可以实现为
    Array.prototype.clone = function() { return this.slice(0); }

如果可以修改原始数组

,只需传递一个本身

答案 2 :(得分:1)

长阵列的更快方法是:

var one = new Array();
one.push(20061001);
one.push(20061002);
one.push(20061003);
one.push(20061120);
var two = new Array();
two.push(3.0);
two.push(3.1);
two.push(3.2);
two.push(3.3);
function NoisyData() {
var ret = [];
ret.push("Date,A");
for (var i=0;i<one.length;i++){
ret.push(one[i]+','+two[i]);
}
 return ret.join('\n');
}
alert(NoisyData());

答案 3 :(得分:1)

您的代码可以缩短很多。您无法在javascript中键入变量(例如Array one)。要在大多数情况下声明一个数组Array literal就足够了 如果你的数组具有相同的长度,你可以使用这里的代码将它们组合成你需要的字符串:

var one = [20061001,20061002,20061003,20061120]
  , two = [3.0,3.1,3.2,3.3]
  , combine = function(a1,a2){
       var i = -1, len = a1.length, res = ['Date,A'];
       while(++i < len){
          res.push(a1[i]+','+a2[i].toPrecision(2));
       }
       return res.join('\n');
    }(one,two);

试试@ http://jsfiddle.net/KooiInc/jdn6U/