javascript将对象数组的值作为数组获取所有键
如何将对象数组的值作为数组获取所有键 例如,我希望将所有src键作为assetloader的数组:javascript将对象数组的值作为数组获取所有键,javascript,arrays,Javascript,Arrays,如何将对象数组的值作为数组获取所有键 例如,我希望将所有src键作为assetloader的数组: images = [ {"name":"an image","src":"http://source.png"}, {"name":"an image2","src":"http://source2.png"}, {"name":"an image3","src":"http://source3.png"} ]; //the solution code here.. c
images = [
{"name":"an image","src":"http://source.png"},
{"name":"an image2","src":"http://source2.png"},
{"name":"an image3","src":"http://source3.png"}
];
//the solution code here..
console.log(solution);
// Output:
// ["http://source.png", "http://source.png2","http://source3.png"]
我可以循环遍历images数组,并将所有的'src'标记推送到solutionvar中,但我认为这在性能方面不是一个好的实践
另外,我不能使用原始image.src标记,assetloader来自一个框架,只接受带有源的数组。您可以使用本机
map
函数进行此操作
var solution = images.map(function (img) {
return img.src;
})
console.log(solution);
你为什么这么想?如果不完全是您所描述的,那么您希望解决方案显示什么样的代码呢?假设我有一个包含10000个图像的数组。我认为,将所有图像转换为一组图像将提高性能。src@Ismail:你分析过它吗?这里没有比O(n)更好的算法,因为你必须在某一点上点击
图像的每个条目。你不能只使用原始图像数组而不是(部分)复制它吗?这将节省您担心的大部分开销;只要您的映像太少,assetloader就可以轻松地加载它们,那么可能不会有实际的性能问题…;-)