我有一個國家物件陣列,(countries)我試圖只獲取一個String名稱陣列,所以從這個例子中:
只是:['Canada', 'USA', ..]等等。
我正在嘗試這樣做
const getNames = (countries) => countries.map(({ Name }) => Name);
但我似乎無法理解。有什么建議?
uj5u.com熱心網友回復:
只是這個?
const getNames = countries.map(c => c.Name);
uj5u.com熱心網友回復:
雖然主題說“沒有”回圈,但實際上你不能。Map 方法還創建了內部回圈演算法。所以基本上你可以做一些非常簡單和非常有效的事情,比如標準for回圈。
// Array of objects
const arr = [
{ id: 1, Name: "Canada", isSelected: false },
{ id: 2, Name: "USA", isSelected: false },
{ id: 3, Name: "India", isSelected: false }
];
// Function to get all params by name
const getAllParam = (arr, param, res = []) => {
for(const e of arr) if(e[param]) res.push(e[param]);
return res;
};
// Get all params with "Name" key
const res = getAllParam(arr, "Name");
// Test
console.log(res);
uj5u.com熱心網友回復:
您已經非常接近正確了;只需洗掉(countries) => 即可。
const getNames = countries.map(({ Name }) => Name);
或者,您可以保留您的代碼,這是一個函式。要獲取國家/地區的名稱- 呼叫該函式并作為引數coNames傳遞。countries
const getNames = (countries) => countries.map(({ Name }) => Name);
const countries = [{id: ...., Name:.........}];
const coNames = getNames( countries );
您的代碼相當于:
const getNames = function( countries ) {
return countries.map(function({Name}) {
return Name;
});
};
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/439882.html
標籤:javascript 数组 目的
