我有 2 个对象数组。第一个里面有 1 个对象,第二个里面有 100 个。
最佳答案
Array.forEach 可以采用三个参数:
元素、索引、数组
尝试进入数组并检查其长度,如下所示:
var myItems = o.getAggregation("ooo")[0].getItems();
myItems.forEach(function(item, index, array){
if(array.length > 1) {/*do whatever*/}
})
Here's引用和第一个示例显示您接受数组参数。
更新示例:
function demo(data) {
data.forEach(function(item, index, array){
if(array.length === 1) {
console.log("Array with one element: ", array);
} else {
console.log("Array with three elements, so gets called thrice: ", array);
}
});
}
var myItems = ["1"];
demo(myItems);
myItems = ["1","2","3"];
demo(myItems);
输出如下:
Array with one element: [ '1' ]
Array with three elements, so gets called thrice: [ '1', '2', '3' ]
Array with three elements, so gets called thrice: [ '1', '2', '3' ]
Array with three elements, so gets called thrice: [ '1', '2', '3' ]
关于javascript - 如果数组长度大于 1 则运行代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38948684/