【问题标题】:running code if length of array is greater than 1如果数组长度大于 1,则运行代码
【发布时间】:2016-08-15 02:51:12
【问题描述】:

我有 2 个对象数组。第一个里面有 1 个对象,第二个里面有 100 个。

【问题讨论】:

    标签: javascript jquery arrays html indexing


    【解决方案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' ]
    

    【讨论】:

    • 它对我不起作用..你能使用上面的代码吗
    • 我试过这个,它只检查第一个数组是否有多个对象。它没有检查第二个数组。
    猜你喜欢
    • 1970-01-01
    • 2013-04-10
    • 1970-01-01
    • 1970-01-01
    • 2015-06-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多