如何返回数组之前的2个元素?

我只是寻找最简单的方法来检查对象数组中的任何字段的值是否为0,并返回包含值0的对象之前的前两个对象。

for(var = 0; i <= result.length; i++) { //so in my case, it will return result[1] and result[2] } 

我应该怎么做呢?

myresult数据

 result = [ { A: 1, B: 2, C: 41, D: 124 }, { A: 123, B: 221, C: 397, D: 81 }, { A: 123, B: 412, C: 400, D: 454 }, { A: 0, B: 412, C: 400, D: 454 }] 

它可以以一种简单的方式完成:循环遍历对象,并为每个对象遍历其属性,一旦find零就返回前两个项目(按索引):

 let result = [{ A: 1, B: 2, C: 41, D: 124}, { A: 123, B: 221, C: 397, D: 81}, { A: 123, B: 412, C: 123, D: 454}, { A: 0, B: 21, C: 53, D: 81}] const getLastTwo = (objArray) => { for (let obj of objArray) { for (let prop in obj) { if (obj[prop] === 0) { const index = objArray.indexOf(obj) return [objArray[index-2], objArray[index-1]] } } } return [] // if we got here - no such element was found! } console.log(getLastTwo(result)) // [ { A: 123, B: 221, C: 397, D: 81 }, { A: 123, B: 412, C: 123, D: 454 } ] 

有很多方法可以做到这一点,但在我看来, map是一个很好的方法。

要获得所有的对象的关键,你可以使用Object.keys如下

 var result = [{ A: 1, B: 2, C: 41, D: 124}, { A: 123, B: 221, C: 397, D: 81}, { A: 123, B: 412, C: 123, D: 454}, { A: 0, B: 21, C: 53, D: 81}] result.map((temp)=>{ console.log(temp); Object.keys(temp).map((temp1)=>{console.log(temp1+":"+temp[temp1])}) }); 

这是奇怪的具体,但这将做到这一点,并不会抛出错误,如果数组中的第二个项目有一个0值。

 let objArr = [ { A: 1, B: 2, C: 41, D: 124}, { A: 123, B: 221, C: 397, D: 81}, { A: 123, B: 412, C: 123, D: 454}, { A: 0, B: 21, C: 53, D: 81}] let res = []; objArr.forEach((obj, i) => { Object.keys(obj).forEach(key => { if(obj[key] === 0){ res.push(objArr[i - 1]); if(objArr[i - 2]){ res.push(objArr[i - 2]) } } }) }) console.log(res) //-> [{ A: 123, B: 221, C: 397, D: 81}, { A: 123, B: 412, C: 123, D: 454},] 

你可以像这样使用ES6 Array#findIndexArray#slice

 function getTwo(arr) { let index = arr.findIndex(o => Object.keys(o).some(k => o[k] === 0)); // get the index of the object whose some of his properties have the value 0 return index < 0? // if the index is -1 (no such object is found) arr.slice(-2): // then return the last two elements of the array arr.slice(Math.max(index - 2, 0), index); // otherwise return two object that occur right before the 0-object (if there is less than two then return as much as possible that's why we use Math.max in case index - 2 is negative) }