查找不带逗号的字符串

时间:2017-07-21 12:59:37

标签: javascript jquery

我有这个代码,我在其中找到字符串值以逗号分隔的键



batch_number | test,b
temp | ,,67,6,87,86,5,67865,876,67
integrity | ,,,,,,,,,,,,,,,,,,,,,,,
weight | 760,765,755,758,759,758,758,769,758,762,759,7




如您所见,我可以检索这些值

Client A: can fetch data from schema X
Client B: can fetch data from schema Y
Client C: can fetch data from schema X and Y

现在我想知道如果有一种方法可以检索没有逗号

的值

4 个答案:

答案 0 :(得分:3)

indexOf(',') > -1更改为indexOf(',') == -1



var db = {
    	"name": "Nkosana",
    	"middle": "Baryy",
    	"surname": "walked",
    	"batch_number": "test,b",
    	"temp": ",,67,6,87,86,5,67865,876,67",
    	"integrity": ",,,,,,,,,,,,,,,,,,,,,,,",
    	"weight": "760,765,755,758,759,758,758,769,758,762,759,7",
    	"comment": "oh la la",
    };

for (var key in db) {
  if (db.hasOwnProperty(key)) {
  	if(db[key].indexOf(',')==-1){
       console.log(key+' | ' + db[key]);
    }
  }
}




答案 1 :(得分:2)

试试这个:



var db = {
    	"name": "Nkosana",
    	"middle": "Baryy",
    	"surname": "walked",
    	"batch_number": "test,b",
    	"temp": ",,67,6,87,86,5,67865,876,67",
    	"integrity": ",,,,,,,,,,,,,,,,,,,,,,,",
    	"weight": "760,765,755,758,759,758,758,769,758,762,759,7",
    	"comment": "oh la la",
    };

for (var key in db) {
  if (db.hasOwnProperty(key)) {
  	if(db[key].indexOf(',')==-1){
       console.log(key+' | ' + db[key]);
    }
  }
}




答案 2 :(得分:2)

只需将if(db[key].indexOf(',')>-1)更改为if(db[key].indexOf(',') == -1)

这是您的更新代码:

var db = {
        "name": "Nkosana",
        "middle": "Baryy",
        "surname": "walked",
        "batch_number": "test,b",
        "temp": ",,67,6,87,86,5,67865,876,67",
        "integrity": ",,,,,,,,,,,,,,,,,,,,,,,",
        "weight": "760,765,755,758,759,758,758,769,758,762,759,7",
        "comment": "oh la la",
    };

for (var key in db) {
  if (db.hasOwnProperty(key)) {
    if(db[key].indexOf(',') == -1){
       console.log(key+' | ' + db[key]);
    }
  }
}

答案 3 :(得分:1)

As I mentioned in my comment,修复很简单。您只需稍微更改if条件:

if(db[key].indexOf(',')==-1){ ... }

这是因为当要搜索的字符串中不存在搜索字符串时indexOf返回-1。

完整的代码清单是:



var db = {
    	"name": "Nkosana",
    	"middle": "Baryy",
    	"surname": "walked",
    	"batch_number": "test,b",
    	"temp": ",,67,6,87,86,5,67865,876,67",
    	"integrity": ",,,,,,,,,,,,,,,,,,,,,,,",
    	"weight": "760,765,755,758,759,758,758,769,758,762,759,7",
    	"comment": "oh la la",
    };

for (var key in db) {
  if (db.hasOwnProperty(key)) {
  	if(db[key].indexOf(',') == -1){
       console.log(key+' | ' + db[key]);
    }
  }
}