English 中文(简体)
Java印号的加固
原标题:Concatenating string with number in Javascript

I m trying to create a simple calculator in Javascript. I have an array named expression chunk[0] = 12 chunk[1] = + (the "+" sign) chunk[1] = 5

我曾用 lo子(草) lo,然后加入如下单一表述:

equation = ""; // To make var equation a string

for(i = 0; i <= length; i++)
{
    equation = equation + expression[i];
    alert(expression[i]);
}

alert(equation);

alert(expression[i]) showed values 12, + and 5. But alert(equation) showed 125 (instead of "12+5"). I need the variable equation to be "12+5" so that I can later call eval(equation) and get the value of 12+5.

我在这里做了什么错误?

问题回答

如果您有chunk = [12, + , 5];, 那么你可以做var eq = chunk.join(");,然后通过

你做了哪些错误? 你们有一个小体。

修订关于这个问题的法典

chunk[0] = 12
chunk[1] =  + 
chunk[1] = 5

纽约总部

chunk[0] = 12
chunk[1] =  + 
chunk[2] = 5

And everything should work.

Why this works: Both the + and the 5 are being assigned 纽约总部chunk[1], with the 5 over-writing the previous assignment ( 纽约总部chunk[1]) of +. This also explains why the concatenated value displayed is 125

In order, the first assignment results in a collection with
a member chunk[0] and a content of 12

The second assignment adds a new member, and results in a collection with
a member chunk[0] whose content is 12
a member chunk[1] whose content is +

The third assignment overwrites the 2nd member, and results in a collection with
a member chunk[0] whose content is 12
a member chunk[1] whose content is 5

all=125

希望化=<代码>12+5





相关问题
selected text in iframe

How to get a selected text inside a iframe. I my page i m having a iframe which is editable true. So how can i get the selected text in that iframe.

How to fire event handlers on the link using javascript

I would like to click a link in my page using javascript. I would like to Fire event handlers on the link without navigating. How can this be done? This has to work both in firefox and Internet ...

How to Add script codes before the </body> tag ASP.NET

Heres the problem, In Masterpage, the google analytics code were pasted before the end of body tag. In ASPX page, I need to generate a script (google addItem tracker) using codebehind ClientScript ...

Clipboard access using Javascript - sans Flash?

Is there a reliable way to access the client machine s clipboard using Javascript? I continue to run into permissions issues when attempting to do this. How does Google Docs do this? Do they use ...

javascript debugging question

I have a large javascript which I didn t write but I need to use it and I m slowely going trough it trying to figure out what does it do and how, I m using alert to print out what it does but now I ...

Parsing date like twitter

I ve made a little forum and I want parse the date on newest posts like twitter, you know "posted 40 minutes ago ","posted 1 hour ago"... What s the best way ? Thanx.

热门标签