Javascript arrays and calculations [closed]

-1

I'm trying to create a array of Strings and give a value to each of the elements. Then calculate the length of each String and multiply each one by the previous multiplication. But it does not work.

<h2> DEMO </h2>

<p id="demo"></p>

<script type="text/javascript">
var s,x=1;
var txt="";
String [] d = {"1X", "1", "X2", "1X2", "1", "1X", "X2", "1", "1X2", "1", "2", "1X", "X2", "2"};
Int [] e = [14];

for (s=0;s<=13;s++){
    e[s]=(d[s].length);
    x=x*e[s];
    txt = s + " " + d[s] + " " + x + "<br>";
}
document.getElementById("demo").innerHTML = txt; 
</script>
    
asked by csvicuna 08.06.2018 в 19:34
source

2 answers

3

If you want to multiply the length then you can use this.

var d = ["1X", "1", "X2", "1X2", "1", "1X", "X2", "1", "1X2", "1", "2", "1X", "X2", "2"];
var result = 1;
d.forEach(function(e) {
  result *= e.length
});
document.getElementById("demo").innerHTML = d.length > 0 ? result : 0;
<div id="demo"></div>
    
answered by 08.06.2018 в 19:50
1

I think that's how you solve it by having several things in the code that I think are the ones that were wrong ...

<script type="text/javascript">
var s=0;
var x=1;
var txt="";
var d = {"1X", "1", "X2", "1X2", "1", "1X", "X2", "1", "1X2", "1", "2", "1X", "X2", "2"};
var e = [14];

for (s=0;s<=13;s++){
    e[s]=d[s].length;
    y=e[s]; 
    x=x*y;
    txt = txt + s + " " + d[s] + " " + x + "<br>";
}
document.getElementById("demo").innerHTML = txt; 
</script>
    
answered by 09.06.2018 в 19:09