1

我有这样的数组:

var notes = ["user1,date:13/2/2008,note:blablabla", "user1,date:15/2/2008,note:blablabla", "user1,date:17/2/2008,note:blablabla", "user1,date:13/3/2008,note:blablabla"];

我有

var search_date="17/2/2008";

我想找到该笔记的最后一次出现的笔记和用户。有谁知道怎么做?提前感谢您的回复。

4

7 回答 7

1
var match = JSON.stringify(notes).match("\"([^,]*),date\:"+search_date+",note\:([^,]*)\"");
alert(match[1]);
alert(match[2]);

作品;-)

于 2013-07-05T13:54:30.660 回答
1

您可以迭代数组并检查属性

或者

你可以使用 underscore.js:http ://underscorejs.org/#filter

于 2013-07-05T13:49:55.033 回答
1

尝试这个:

var highestIndex = 0;
for (var i = 0; i < notes.length; i++){
    if (notes[i].indexOf(search_date) != -1){
        highestIndex = i;
    }
}
//after for loop, highestIndex contains the last index containing the search date.

然后要获取用户,可以这样解析:

var user = notes[highestIndex].substring(0, notes[highestIndex].indexOf(',') - 1);
于 2013-07-05T13:50:29.980 回答
1
for (var i = 0; i < notes; i++) {
    if (notes[i].indexOf(search_date) != -1) {
        // notes [i] contain your date
    }
}
于 2013-07-05T13:51:07.240 回答
0

对于最后一次出现,如果性能很重要:

var notes = ['user1,date:13/2/2008,note:blablabla', 'user1,date:15/2/2008,note:blablabla', 'user1,date:17/2/2008,note:blablabla', 'user1,date:13/3/2008,note:blablabla'],
    search = '17/2/2008',
    notesLength = notes.length - 1,
    counter,
    highestIndex = null;

for (counter = notesLength; counter >= 0; counter--) {
    if (notes[counter].indexOf(search) !== -1) {
        highestIndex = counter;
        break;
    }
}

// do something with notes[highestIndex]
于 2013-07-05T13:58:33.350 回答
0
var notes = ["user1,date:13/2/2008,note:blablabla", "user1,date:15/2/2008,note:blablabla", "user1,date:17/2/2008,note:blablabla", "user1,date:13/3/2008,note:blablabla"];

var search_date="17/2/2008";
var user, note;

$.each(notes, function(i) {
    var search = new RegExp('\\b' + search_date + '\\b','i');
    // if search term is found
    if (notes[i].match(search)) {
      var arr = notes[i].split(',');
      user = arr[0];
      note = arr[2].substr(5);
    }
}); // end loop

console.log(user);
console.log(note);

这里的例子:http: //jsfiddle.net/Misiu/Wn7Rw/

于 2013-07-05T13:59:17.490 回答
0

像这样的东西:

var notes = ["user1,date:13/2/2008,note:blablabla", "user1,date:15/2/2008,note:blablabla", "user1,date:17/2/2008,note:blablabla", "user1,date:13/3/2008,note:blablabla"];
var search_date="17/2/2008";

var res = [];

for(var i = 0; i < notes.length; i++) {
  var note = notes[i];
  if(note.indexOf(search_date) !== -1) {
    res.push(note.substring(note.indexOf('note:') + 1), note.length);
  }
}

var noteYouWanted = res[res.length - 1];
于 2013-07-05T13:53:07.083 回答