我有一些东西
var officers = [
{ id: 20, name: 'Captain Piett' },
{ id: 24, name: 'General Veers' },
{ id: 56, name: 'Admiral Ozzel' },
{ id: 88, name: 'Commander Jerjerrod' }
];
我需要返回“ 20”,“ 24”,“ 56”,“ 88”
现在我正在使用
const ids = officers.map(officer => officer.id);
但它当然会返回我一个数组。
最有效的方法是什么?
答案 0 :(得分:4)
您可以使用map()
以""
返回字符串数组,然后使用join()
var officers = [
{ id: 20, name: 'Captain Piett' },
{ id: 24, name: 'General Veers' },
{ id: 56, name: 'Admiral Ozzel' },
{ id: 88, name: 'Commander Jerjerrod' }
];
const res = officers.map(x => `"${x.id}"`).join()
console.log(res)
答案 1 :(得分:0)
您可以在地图上用引号引起来,然后调用Array.join。
const ids = officers.map(officer => '"' + officer.id + '"').join();
答案 2 :(得分:0)
最有效的方法是什么?
Array.map每次都会创建一个新函数并调用它,那效率不高。
最有效的方法是使用普通的for循环:
var res = '';
for(let {id} in officers){
res+=....
}
但是现在您将每次创建一个新字符串(res+=...
)。
如果您不必处理很多字符串,那绝对可以,但是在这种情况下,您可能需要切换到数组并将其连接到字符串的末尾。