9-30钟诚

let a = [
{time:1},
{time:5},
{time:8},
{time:11},
{time:16},
{time:17},
{time:29},
{time:34},
{time:39}

];

time_line = [3,7,12,17,19,31,40];

请找出,根据time_line,找到a数组中最近的一个数,如果相等,取后面一个,数组a的值只能被取一次
返回结果 [{line:3,time:5},{line:7,time:8}]

function array(line) {

​ let a = [{ time: 1 }, { time: 5 }, { time: 8 }, { time: 11 }, { time: 16 },

​ { time: 17 }, { time: 29 }, { time: 34 }, { time: 39 }

​ ];

​ var b = [] //定义空数组b 遍历a数组 获取值 存入b数组中

​ for (var i = 0; i < a.length; i++) {

// console.log(a[i].time)

​ b.push(a[i].time) // 获取a[i].time值 存入b数组中

​ }

​ var abs = []; //定义abs空数组 承接line之中每一个数与 b数组的每一个数做差

​ var abs1 = [];//存放line与b的差值

​ arr2 = [];//

​ var start = 0;

​ for (let j = 0; j < line.length; j++) { //line之中每一个数与 b数组的每一个数做差

​ for (let z = 0; z < b.length; z++) {

​ abs1.push(Math.abs(line[j] – b[z])) //abs1 存放line每一项与b数组每一项的差值

​ }

​ }

​ for (k = 0; k < line.length; k++) {

​ end = start + 9

​ arr2[k] = abs1.slice(start, end);//因为 a数组有9个对象 所以line每一项和其做差会的返回9个数存入abs1中, arr2二维数组 将arr1分为每个片段 存入 其中每一项分别对应line数组每一项对a[i].time的差存储

// console.log(abs1.slice(start, end))

​ start = end;

​ var arr3 = arr2[k];

// arr2 = arr2 + arr2[k]

​ var minNum = Math.min(…arr3); //求到每一次中 的最小值 就可以知道越小 越接近 ,而为0就是相等

​ console.log(minNum);

​ if (arr3[0] !== arr3[1]) {

​ console.log(a[arr2[k].indexOf(minNum)])

​ } else if (arr3[0] == arr3[1]) {

​ console.log(a[arr2[k].indexOf(minNum) + 1])

​ }

​ }

​ }

​ array([3, 7, 12, 17, 19, 31, 34, 40])

总结 :晚上没有复习,全浪费在这道题,但是做不出来心理又不舒服

评论

this is is footer