Kam*_*ski 0 javascript arrays properties object
我希望有可重用的函数,它根据作为参数传递给属性的属性映射对象数组.
这是我的代码:
let arr = [
{
country: 'poland',
population: 380000
},
{
country: 'bangladesh',
population: 3492423
}
]
function filterMyArr (myArr, condition) {
return myArr.map(element => element.country)
}
console.log(filterMyArr(arr))
Run Code Online (Sandbox Code Playgroud)
当我更改代码并尝试传递条件时,执行它时不起作用.我想用第二个参数调用一个函数,例如filterMyArr(arr,country),并得到类似的结果.我希望它可以重复使用,所以我可以将它用于人口或任何其他财产.谢谢.
你只需要使用括号表示法,如下所示:
function filterMyArr (myArr, condition) {
return myArr.map(element => element[condition])
}
Run Code Online (Sandbox Code Playgroud)
当你通过condition一个string在你的属性的名称object.
注意:
但是请注意,调用没有此condition参数的函数会产生错误,当您执行以下操作时:
console.log(filterMyArr(arr))
Run Code Online (Sandbox Code Playgroud)