当前位置: 动力学知识库 > 问答 > 编程问答 >

How do I get the OR operator to work in this JavaScript array

问题描述:

I have been wrestling with this issue off and on for a couple of months now. Is there away to apply the "OR" operator in to this array structure below?

Basics: If the value in a dropdown matches the value(s) in the array, then the corresponding ID is sent to a function and it does some other stuff, but I have not been able to add/include the OR operator.

For example I want to be able to say in the code:

{id : '418', value: 'Brochure' || 'Broc'},

{id : '546', value: 'Classified Ad' || 'CA' || 'Class Ad'},

But the above never works, so I don't know if it just can't be done or I have the syntax wrong.

Any insight would be appreciated greatly.


Function that is run once value is found

var projectTypes = [{

"id": "418",

"value": ["Brochure", "Broc"]

}, {

"id": "546",

"value": ["Classified Ad", "CA", "Class Ad"]

}, {

"id": "254",

"value": ["Flyer", "Flyers"]

}, {

"id": "855",

"value": "Post Card"

}];

function projectTypeChange() {

var project_type = document.getElementById(projectType_Field_Id).value;

SwitchBox(project_type);

}

function SwitchBox(selectedType) {

for (var i = 0; i < projectTypes.length; i++) {

if (projectTypes[i].value.indexOf(projectTypes) >= 0)

//if (projectTypes[i].value == selectedType)

{

document.getElementById("section-" + projectTypes[i].id).style.display = '';

} else {

document.getElementById("section-" + projectTypes[i].id).style.display = 'none';

}

}

}

网友答案:

Do what Justin suggested. Change this line in your indexof code:

if(projectTypes[i].value.indexOf(projectTypes) >= 0)

to this:

if(projectTypes[i].value.indexOf(selectedType) >= 0)
网友答案:

Instead of trying to use the || operator (which is incorrect in this case), make the value its own array:

{ id: '418', value: ['Brochure','Broc'] },
{ id: '546', value: ['Classified Ad','CA','Class Ad'] }

Then instead of checking for equality against value, check indexOf to see if the value is in the array:

if(value.indexOf(someVal) >= 0)
{
    // someVal was found in the value array...do the work!
}
分享给朋友:
您可能感兴趣的文章:
随机阅读: