我编写了以下代码,在数组中查找字符串标记。
var parseCSVLines = function(lines) {
var valueObj = {};
var delim = ',';
var isLayer = false;
var isGroup = false;
for(var i = 0; i < lines.length; i++){
//skips CR/CF lines
if(!lines[i]) continue;
//only data lines reach this loop
var data = lines[i].split(delim);
/*********looks for tag*************/
if(data[0] == '#L' || data[0] == '#l'){
//on occasions, data[0] is '#L' or '#G' still execution reaches here
isLayer = true;
}else if(data[0] == '#G' || data[0] == '#g'){
isGroup = true;
}else{
if(isLayer){
valueObj[data[0]] = {
layerInfo: data[1] == 'on' ? true : false
};
}
else if(isGroup){
valueObj[data[0]] = {
GroupInfo: data[1] == 'on' ? true : false
};
}
}
}
return valueObj;
};
我遍历行并标记下一行以获取数据。很奇怪,当data[0]
为'#L'
和'#G'
时,会执行第一个if
语句。我做错了什么?
答案 0 :(得分:1)
if语句没问题,即使你有data[0]='#G#L'
......它永远不会进入data[0]=='#L'||data[0]=='#l'
在我看来,你陷入逻辑 -
if (data[0] == '#L' || data[0] == '#l') {
isLayer = true;
//isGroup=false; you should toggle isGroup
} else if (data[0] == '#G' || data[0] == '#g') {
isGroup = true;
//isLayer=false; you should toggle isLayer
} else { //do you want else here??? This would pick the value of isLayer or isGroup according to previous line processed but not the value according to current line being processed.
if (isLayer) {
valueObj[data[0]] = {
layerInfo: data[1] == 'on' ? true : false
};
} else if (isGroup) {
valueObj[data[0]] = {
GroupInfo: data[1] == 'on' ? true : false
};
}
}
示例:
line1: '#L,hi'
line2:'#G,hi'
line3:'hi'
处理第一行将设置isLayer=true;
处理第二行将设置isGroup=true;//remember isLayer is still true - you haven't set it to false;
处理第三行将触发您的其他部分...并进入if(isLayer)
将true
使其有效:
//update isLayer and isGroup for every iteration to keep the logic inline
isLayer=(data[0] == '#L' || data[0] == '#l');
isGroup=(data[0] == '#G' || data[0] == '#g');
if(!isLayer && !isGroup) {
if (isLayer) {
valueObj[data[0]] = {
layerInfo: data[1] == 'on' ? true : false
};
} else if (isGroup) {
valueObj[data[0]] = {
GroupInfo: data[1] == 'on' ? true : false
};
}
}
答案 1 :(得分:0)
试试这个:
if(data[0] == "#l" || data[0] == "#L") {
if(data[0].search("#g") != -1 || data[0].search("#G") != -1){
}else{
isLayer = true;
}
}else if(data[0] == "#g" || data[0] == "#G"){
if(data[0].search("#l") != 0 || data[0].search("#L") != 0){
}else{
is group = true;
}
}
你知道,你没做的是检查两者是否存在。我的代码所做的就是检查
这确保选择一个且仅选择一个选项。