![](/img/trans.png)
[英]Why is only some of the JSON data posting to the DOM rather than all of it?
[英]Simple value to only return some array elements rather than all
我創建了一個簡單的變量“ indexes
”,該變量成功地標識了數組“ arr
”中的索引為奇數,並且先前的值是奇數,並且不測試第一個數字。 但是,在定義indexs變量時,它最初返回:
[undefined, 1, 2, undefined, undefined]
然后,我必須過濾出未定義的值來實現我想要的( [1,2]
)。
有沒有一種方法可以做到這一點而無需過濾? 我想不出辦法。 另外,有沒有辦法只返回某些元素的數組值而不是像map那樣返回所有值? 我以為可以使用some方法,但是那只會返回一個布爾值,而只是一些項目的數組。
感謝您的幫助。 我的代碼如下:
let arr = ["9", "9", "9", "4", "6"];
let indexes = arr.map(function(c,i,a){if (i != 0 && c % 2 != 0 && a[i-1] % 2 != 0) {return i} }); // [undefined, 1, 2, undefined, undefined]
indexes = indexes.filter(item => item !== undefined); // [1,2]
您可以使用reduce
函數,該函數可讓您遍歷集合並累積所需的任何數據:
let arr = ["9", "9", "9", "4", "6", "7"];
let indexes = arr.reduce((acc, el, index) => {
if (index != 0 && el % 2 != 0 && arr[index-1] % 2 != 0) {
acc.push(index);
}
return acc;
}, []);
實際上,可以使用reduce
輕松實現filter
和map
,因為您可以初始化一個空數組,並且根據回調函數,您可以將元素添加到最終數組中,也可以操縱每個元素的值。
您可以使用數組減少功能
let arr = ["9", "9", "9", "4", "6"]; let indexes = arr.reduce(function(acc, curr, i, a) { if (i !== 0 && curr % 2 !== 0 && a[i - 1] % 2 !== 0) { acc.push(i); } return acc; }, []); console.log(indexes)
是的,有一種方法可以在1行中完成 。
您可以將.reduce
與作為參數傳遞的累加器,元素和索引一起使用。 然后使用三元運算符代替if語句,然后使用擴展語法( ...
)將值壓入/追加到累加器數組:
let arr = ["9", "9", "9", "4", "6"]; const indexes = arr.reduce((acc, elem, i) => (i != 0 && elem % 2 != 0 && arr[i-1] % 2 != 0) ? [...acc, i] : acc, []); console.log(indexes);
注意 :單行代碼並不總是更好,代碼的可讀性很重要,因為它有助於程序的可維護性。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.