1

I have a small piece of code that generates an array with values based on a triangle. I will post the array below.

var endwallPanelLengths = [totalHeightInches];
var i = 0;
while (endwallPanelLengths[i] > eaveInches) 
{
    endwallPanelLengths.push(endwallPanelLengths[i] - peakHeightDecrease);
    document.getElementById("test83").value="4 - " + endwallPanelLengths[i];
    i++;
}

This array will have anywhere between 2 to 100 indexes. I want the code to write all of the values separated by breaks into a <textarea> with the id="test83".
If I run the code as it is set up above it will only write the value in array [1] not [0] or any of the others. How can I get it to write all of them so that they come out looking like this...

4 - 140 this is the value of array position [0]

4 - 126

4 - 116 and so on?

4

3 回答 3

2

你不断更换价值

document.getElementById("test83").value="4 - " + endwallPanelLengths[i];

您需要附加到值

document.getElementById("test83").value += "4 - " + endwallPanelLengths[i] + "\n";

更好的是,建立价值并设置一次价值

var endwallPanelLengths = [totalHeightInches],
    i = 0,
    output = [];
while (endwallPanelLengths[i] > eaveInches) 
{
    endwallPanelLengths.push(endwallPanelLengths[i] - peakHeightDecrease);
    output.push("4 - " + endwallPanelLengths[i]);
    i++;
}
document.getElementById("test83").value = output.join("\n");
于 2013-06-03T19:36:28.183 回答
1

如果我对您的理解正确,您希望数组中的每行显示一个项目textarea,那么您应该能够完全放弃循环,只需一次完成即可。

document.getElementById("test83").value = endwallPanelLengths.join('\n');

尽管看起来您在每个值前面都添加了“4 -”。如果是这种情况,那么您只需添加一个额外的步骤即可添加这些四:

var arr = endwallPanelLengths.map(function(item){ return '4 - ' + item; });
document.getElementById("test83").value = arr.join('\n');

如果您需要支持 IE8,请务必Array.prototype.map此处获取 shim

于 2013-06-03T19:36:17.173 回答
0

HTML:

<div id="holder"></div>

JavaScript:

var endwallPanelLengths = [totalHeightInches];
var i = 0;
var holder =  document.getElementById("holder");
while (endwallPanelLengths[i] > eaveInches) 
{
    endwallPanelLengths.push(endwallPanelLengths[i] - peakHeightDecrease);
    var e = document.createElement('div');
    e.innerHTML = "4 - " + endwallPanelLengths[i] + "<br />";
    holder.appendChild(e.firstChild);
    i++;
}

希望这对你有你想要的。在您的示例中,在您的循环中,您将最新值设置为同一元素,从而覆盖任何以前的值。

于 2013-06-03T19:35:39.677 回答