var arr = ["10/27/2017","11/5/2017","11/5/2017","11/10/2017","11/10/2017","12/12/2017"];
var userDate = "11/10/2017";
如果我想在用户日期之前找到这个(假定排序的)数组中的日期,我该怎么办?所以在这种情况下,我想返回11/5/2017
。
基本上,找到数组中指定日期左侧的下一个最近的对象。更进一步,如果我想再次检查前一个元素是什么,但想避免重复,那将是有帮助的。
答案 0 :(得分:3)
您可以使用Array#indexOf
。
不要忘记检查元素是否存在且不是arr.indexOf(userDate) > 0
let arr = ["10/27/2017","11/5/2017","11/10/2017","11/10/2017","12/12/2017"];
let userDate = "11/10/2017";
let result = arr.indexOf(userDate) > 0 ? arr[arr.indexOf(userDate) - 1] : null;
console.log(result);
答案 1 :(得分:1)
var arr = ["10/27/2017", "11/5/2017", "11/10/2017", "11/10/2017", "12/12/2017"];
var userDate = "11/10/2017";
var prev = arr.indexOf(userDate); // One call to indexOf - DRY
console.log(
prev > 0 ? // neither the first (==0) nor not found (==-1)
arr[prev-1] : "no earlier date"
);
答案 2 :(得分:0)
您可以使用indexOf
获取日期索引。然后很容易得到以前的值。
哟可以尝试以下内容:
var arr = ["10/27/2017","11/5/2017","11/10/2017","11/10/2017","12/12/2017"];
var userDate = "11/10/2017";
var index = arr.indexOf(userDate); // Get the index
var previous = index > 0 ? arr[index - 1] : null; // Check if the date exists. If it does exists get the previous value or set it to null
console.log(previous)

答案 3 :(得分:0)
我认为indexOf
最适合这个问题。
var arr = ["10/27/2017", "11/5/2017", "11/10/2017", "11/10/2017", "12/12/2017"];
var userDate = "11/10/2017";
var index = arr.indexOf(userDate);
var result = "";
if (index < 0) { // no match case
result = 'no match';
} else if (index == 0) { // userdate is first element
result = 'userDate is first element';
} else { // get the result
result = arr[index - 1];
}
console.log('result=', result);
答案 4 :(得分:-2)
arr[arr.indexOf(userData) - 1] ? arr[arr.indexOf(userData) - 1] : throw new Error('...');
如果你坚持。 我更愿意处理在我实际使用它时未定义值的情况。
答案 5 :(得分:-2)
var arr = ["10/27/2017","11/5/2017","11/10/2017","11/10/2017","12/12/2017"];
function findLeft(argum) {
let firstIndex = arr.indexOf(argum);
let leftside = firstIndex - 1;
//you need to figure out error handling for < 0;
return arr[leftside];
}