[英]Loop through JavaScript array and exclude the array itself
我试图遍历从[this.props.dataPro.links]
JSON代码解析的JS对象:
"links" :
[ "/static/media/0.jpg",
"/static/media/1.jpg",
"/static/media/1.jpg" ],
我通过数组键将这些链接插入图像对象:
_getStaticImages() {
let images = [this.props.dataPro.links]
for (var key in images) {
if (images.hasOwnProperty(key)) {
var obj = images[key];
for (var prop in obj) {
if (obj.hasOwnProperty(prop)) {
images.push({
original: obj[prop],
thumbnail:obj[prop]
});
}
}
}
}
return images;
}
结果,我在返回对象的开头得到了一个空的返回对象,当我在images
响应上执行console.log时,似乎还返回了数组对象本身:
[Array[3], Object, Object, Object]
0:Array[4]
1:Object
2:Object
3:Object
如何对数组进行循环排序并排除数组本身?
您正在将初始数组添加到输出let images = [this.props.dataPro.links]
。 相反,您可以在此处理想地使用Array.map:
var linkObj = { "links": [ "/static/media/0.jpg", "/static/media/1.jpg", "/static/media/1.jpg" ] }; function getStaticImages() { let output = linkObj.links.map(imgUrl => { return { original: imgUrl, thumbnail: imgUrl } }); return output; } console.log(getStaticImages());
我将使用Array.prototype.map()
并执行以下操作:
getStaticImages(imageArray) {
return imageArray.map(function(img) {
return {
original: img.whateverPropMapsToOriginal,
thumbnail: img.whateverPropMapsToThumbnail,
}
});
}
var images = [];
for(var i = 0; i < this.props.dataPro.links.length;i++)
{
images.push({
original: this.props.dataPro.links[i],
thumbnail: this.props.dataPro.links[i]
});
}
至于为什么首先将数组作为第一个元素,则此行:
let images = [this.props.dataPro.links]
在其中使用要迭代的数组的第一个元素创建数组images
。
要创建一个空数组,请不要在其中放入任何值:
let images = []; // nothing inside
至于迭代本身。 鉴于this.props.dataPro.links
已经是数组,要遍历它,您应该像这样:
var myArray = this.props.dataPro.links; // so we don’t need to type it later
var images = []; // we’re creating *empty* table
for (var i = 0; i < myArray.length; ++i) {
console.log('Item', i, myArray[i]);
images.push({
original: item,
thumbnail: item
});
}
那是老方法。 如果您支持IE9以上版本,则可以使用Array.prototype.forEach函数:
var images = [];
this.props.dataPro.links.foreach(function (item, index) {
console.log('Item', index, item);
images.push({
original: item,
thumbnail: item
});
}
如果要选择性地中断遍历数组,请不要使用第二种解决方案。
为什么不更改您的for
循环?
for (let i = 1; i > obj.length; i++) {
if (obj[i]) {
images.push({
original: obj[prop],
thumbnail: obj[prop]
})
}
}
这会跳过数组的0th
元素(要跳过的对象),但仍会推送所需的图像。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.