简体   繁体   中英

Using a variable to search an array instead of a static string

Okay, so what I have is basically three dynamic drop down boxes and a 2D array. I have each box adding their values together, and then I want the sum of the values to be searched for through the array to pull out the fifth value on whatever the row the value was on.

var shape = document.getElementById("shape").value;
var dimension_one = document.getElementById("dimension_One").value;
var x = 'x';
var dimension_two = document.getElementById("dimension_Two").value;
var selected_beam = shape + dimension_one + x + dimension_two; // combine all values from text boxes 
alert(selected_beam);

for (i = 0; i < array_shapes.length; i++)
{
    if (array_shapes[i][2] == selected_beam) {
        alert('Area=' + array_shapes[i][5]);
        //Area= array_shapes[i][5]);
    }
}

I know that selected _beam is giving me the value I want, and I also know that the array loop returns what I want out of the array but only if I replace

if (array_shapes[i][2] == selected_beam)

with

if (array_shapes[i][2] == "value I want to search for")

So what I really need to know is - why will it only accept it as a string and not as my selected_beam variable.

Based on your array values, it looks like you need var x to be uppercase like:

var x = 'X';

If I am reading your array correctly, it also looks like the beam size is in element 0 and 1 of the array not 1 and 2, so you may need to not look for array_shapes[i][2], but rather array_shapes[i][0] or array_shapes[i][1]

The first item in the array is at index value = 0.

You need to do some debugging.

To start off, you need to know why selected_beam !== "your value" .

I suggest you use this function to compare the strings:

function compare( s1, s2 ){
  alert("s1: " + s1.toString());
  alert("s2: " + s2.toString());
  if (s1.toString() == s2.toString())
    return alert("true");
  return alert("false");
}

>>> compare(selected_beam,"your value");

The problem might be as simple as having unnecessary characters in your selected_beam .

So where you have alert(selected_beam) , try to compare the strings and see if it returns true or false.

You are concatenating values that you're parsing from a text box. The result will be a string

Try doing:

var selected_beam = parseInt(shape) + parseInt(dimension_one) + parseInt(x) + parseInt(dimension_two);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM