如果数组的长度大于1,则运行代码

时间:2016-08-15 02:51:12

标签: javascript jquery arrays html5 indexing

我有2个对象数组。第一个在其中有一个对象,第二个有100个。

1 个答案:

答案 0 :(得分:1)

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' ]