我目前有一個函式,它為陣列中的每個專案回傳一個值,最多可達一個最大值。看起來像這樣
const myArray = [
{ url: "example.com/1", other: "foo" },
{ url: "example.com/sdf", other: "foo" },
{ url: "example.com/blue", other: "foo" },
{ url: "example.com/foo", other: "foo" },
{ url: "example.com/123", other: "foo" },
];
function getNumberOfUrls(data, num) {
const newArray = [];
data?.forEach(function (datum) {
if (newArray.length < num) {
newArray.push(datum.url);
}
});
return newArray;
}
// Output
//["example.com/1", "example.com/sdf", "example.com/blue"]
它只是回傳url陣列中每個物件的值,直到達到提供的限制。它作業正常,但我試圖探索是否應該使用更合適的 Array 函式。
我知道Array.filter根據迭代項是否通過特定條件創建一個新陣列,但我想知道它是否可以用來檢查其他東西是否通過條件 - 在這種情況下是父陣列。
function getNumberOfUrls(data, num) {
return data.filter(datum => /* return url until we hit .length === num in data? */ )
};
我怎樣才能完成這項作業,或者是否有更適合的 Array 方法來實作這一點?
ETA:原始示例陣列沒有繪制完整的圖片。我現在添加了更多資料來顯示問題。我不想只回傳前三個物件的陣列,我只想回傳url前三個物件的值。
uj5u.com熱心網友回復:
執行此操作的最短方法是使用Array.slice:
const myArray = [
{ url: "example.com/1" },
{ url: "example.com/sdf" },
{ url: "example.com/blue" },
{ url: "example.com/foo" },
{ url: "example.com/123" },
]
const limit = 3
const shorterArray = myArray.slice(0, limit).map(item => item.url)
console.log(shorterArray)
我洗掉了我的其他代碼,因為它效率低下,不應該使用。
uj5u.com熱心網友回復:
一種方法是使用 Array.from() 和它的內部映射器
const myArray = [
{ url: "example.com/1" },
{ url: "example.com/sdf" },
{ url: "example.com/blue" },
{ url: "example.com/foo" },
{ url: "example.com/123" },
];
function getNumberOfUrls(data, num) {
return Array.from({length:num}, (v,i) => data[i].url)
}
console.log(getNumberOfUrls(myArray, 3))
uj5u.com熱心網友回復:
給定一個 JavaScript 陣列,你如何只得到它的前 X 項?
使用每個陣列實體自帶的內置 slice() 方法:(注意本次操作不會修改原始陣列。)
const myArray = [
{ url: "example.com/1", other: "foo" },
{ url: "example.com/sdf", other: "foo" },
{ url: "example.com/blue", other: "foo" },
{ url: "example.com/foo", other: "foo" },
{ url: "example.com/123", other: "foo" },
];
const limit = 3 //get the first 3 items
const newArray = myArray.slice(0,limit).map( (item) => {return {url:item.url} })
console.log(newArray)
uj5u.com熱心網友回復:
您可以簡單地設定新映射陣列的長度
編輯:.map()用作最終陣列與起始陣列不同(只是最終陣列中的 url,而不是起始陣列中的物件)
const myArray = [
{ url: "example.com/1" },
{ url: "example.com/sdf" },
{ url: "example.com/blue" },
{ url: "example.com/foo" },
{ url: "example.com/123" },
];
function getNumberOfUrls(data, num) {
let newArray = data.map(el => el.url);
newArray.length = num;
return newArray;
}
console.log(getNumberOfUrls(myArray, 3))
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/416673.html
標籤:
