【问题标题】:Return true if it's first non-empty array如果它是第一个非空数组,则返回 true
【发布时间】:2016-08-01 01:11:34
【问题描述】:

我有一个包含两种类型数据的对象:ArrayString

{
  "livingroom": [
    {
      "app": "",
      "name": "s1",
      "thumbnail": "https://storage.googleapis.com/peterbucket/istagingViewer/sigstaging.com.tw/Cuiti/study/web/thumb_floorplan1.jpg"
    }
  ],
  "study": [
    {
      "app": "",
      "name": "s0",
      "thumbnail": "https://storage.googleapis.com/peterbucket/istagingViewer/sigstaging.com.tw/Cuiti/study/web/thumb_floorplan3.jpg"
    }
  ],
  "outdoor": [],
  "id": "-KF28-_Vdve-u3498eQ1",
  "name": "Cuiti"
}

现在我正在遍历所有值,并且我只想返回第一个非空数组(在本例中为 livingroom 的值)。

// Template
<div v-for="value in object" v-if="isFirstNonEmptyArray(value, object)">

// JavaScript
isFirstNonEmptyArray (value, object) {
  if (value instanceof Array) {
    if (value.length > 0) {
      // What to do here?
    }
  }
},

但正如您所见,在检查该值不为空后我被卡住了。接下来我应该写什么?

【问题讨论】:

  • 您不应该依赖对象属性的顺序。如果您想保持秩序,请使用数组。

标签: javascript arrays vue.js


【解决方案1】:

希望这段代码有用。 Js obejct不保证其键的顺序,所以只找出那些是数组且非空的键

var _localArray = [] // Use to store non empty array 
    for(var keys in a){ // Iterating over object. a is the object
    // Checking if the current key is an array & it's length is >= 1
    if(Object.prototype.toString.call(a[keys] ) === '[object Array]' && a[keys].length>=1) {
      _localArray.push(a[keys]);  // push the key in temp array
    }
    }
    console.log(_localArray[0]); // will log the first non empty array

jsfiddle

【讨论】:

    【解决方案2】:

    这是一个棘手的问题,因为 Javascript 对象的属性没有排序

    换句话说,因为no loop through the object properties is guaranteed to hit them in the same order,很难返回first这样的空值属性。因此,如果该属性是对象中的第一个这样的值,则不可能返回true,因此您的问题无法按说明解决:)

    如果您只有 一个 长度非空的属性,那么您可以做的最好的事情是:

    function FirstNonEmptyArray(object) {
        for (var property in object) {
            if (object.hasOwnProperty(property) && (object[property] instanceof Array)) {
                if (object[property].length > 0) {return property;}
           }
    }};
    

    如果您有多个具有非空长度的属性,则无法保证通过对象的迭代顺序。这些属性中的任何一个都可以返回。

    如果属性名称的长度不为零,则最好将它们附加到数组中,然后按照您的意愿处理它们:

     function AllNonEmptyArrays(object) {
        var array = []
        for (var property in object) {
            if (object.hasOwnProperty(property) && (object[property] instanceof Array)) {
                if (object[property].length > 0) {array.push(property);}
           }
        return array;
    }};
    

    【讨论】:

      猜你喜欢
      • 2017-01-29
      • 1970-01-01
      • 2017-02-06
      • 1970-01-01
      • 2018-01-04
      • 1970-01-01
      • 2016-02-17
      • 2022-01-12
      • 2017-09-02
      相关资源
      最近更新 更多