我想问一下,为了达到这个目的,我是否有更好的解决方案:
输入
arr = [
{value:1, role:""},
{value:2, role:""},
{value:4, role:""},
{value:5, role:""}
];
输出
outputArr = [1, 2, 4, 5];
到目前为止,我的解决方案是:
for(var i = 0; i < arr.length; i++){
outputArr.push(arr[i].value);
}
但是有更好的方法吗?
答案 0 :(得分:3)
您可以改用Array#map()
:
let arr = [
{value:1, role:""},
{value:2, role:""},
{value:4, role:""},
{value:5, role:""}
];
let output = arr.map(el => el.value);
console.log(output)
答案 1 :(得分:1)
let arr = [
{value:1, role:""},
{value:2, role:""},
{value:4, role:""},
{value:5, role:""}
];
let outputArr = arr.map((e)=>e.value)
console.log(outputArr)
答案 2 :(得分:1)
查看此
arr = [
{value:1, role:""},
{value:2, role:""},
{value:4, role:""},
{value:5, role:""}
];
var d=arr.map((x)=>x.value)
console.log(d)
您可以检查哪一个速度更快
arr = [
{value:1, role:""},
{value:2, role:""},
{value:4, role:""},
{value:5, role:""}
];
console.time('Using Loop');
var aOut=[];
for(var i = 0; i < arr.length; i++){
aOut.push(arr[i].value);
}
console.timeEnd('Using Loop')
console.time('Using Map');
var bOut = arr.map((e)=>e.value)
console.timeEnd('Using Map')