开发者

Split function going Abnormal in JavaScript

This is the Contents of file from where i am reading...

aaa 3333,bbb 5,ccc 10

I am getting un defined for the keyvalue[2], [3], [4] and [5]. Why is 开发者_如何学Cit so???

I am actually first spliting based on , and then based on space.


because you split by comma first, so item is now 'PrimeSuiteId 3333'. When you split that by space you get two items only, so 3rd value (keyvalue[2]) and above is empty.


Edit: possible fix to make second part of your script work

swap

var items = contents.toString().split(',');

with

var items = contents.toString().replace(/,/,' ');

which will simply replace commas with spaces in the original string so your array of expected values matches up


Another edit: because splitting by comma or space is better (as in comments)

var contents = f.read();
  Ti.API.info(contents);
  var items = contents.toString(); // changed to return complete string not split
  // removed for loop altogether
  var keyvalue = items.split(/,|\s/);  // changed to split by comma or space
  var AppointmentSearchDaysAfter = keyvalue[0];  
  var AppointmentSearchDaysAfterValue = keyvalue[1];
  var AppointmentSearchDaysBefore = keyvalue[2];  
  var AppointmentSearchDaysBeforeValue = keyvalue[3];
  var PrimeSuiteId = keyvalue[4];  
  var PrimeSuiteIdValue = keyvalue[5]; 


From the contents in the contents file you should only be able to get values for

var AppointmentSearchDaysAfter = keyvalue[0];       
var AppointmentSearchDaysAfterValue = keyvalue[1]; 

You only have one space for each data entry between the commas


Split function is working fine, you are expecting it to behave abnormal.

You will get only two values in array after split by space. From where will it bring 6 values!!!?

The rest values you will get in next iterations.


Instead of declaring individual variables for each item and then loading them from the contents string, you can reduce the whole thing to an object with key/value pairs:

var items = contents.split(',').reduce(function (acc, val) {
    var split = val.split(' ');
    return acc[split[0]] = split[1], acc;
}, {});

To test what the values are, try:

console.log(items.PrimeSuiteId); // outputs 3333
console.log(items.AppointmentSearchDaysBefore); // outputs 5
console.log(items.AppointmentSearchDaysAfter); // outputs 10
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜