unexpected token break in ternary conditional

前端 未结 2 1836
别跟我提以往
别跟我提以往 2021-01-27 05:08

The function below is intended to return the values from a (potentially nested) object as an array - with the list parameter being any object. If I move my break statement to af

2条回答
  •  难免孤独
    2021-01-27 05:37

    In case anyone else has this issue: ternary operators only work with value expressions, not statements (like break) and aren't meant to be used in these cases.

    This works:

    function listToArray(list) {
        var objectArray = [];
        function objectPeeler() {
            let peel = Object.getOwnPropertyNames(list);
            for(var i = 0; i < peel.length; i++) {
                list[peel[i]] != null && typeof list[peel[i]] != 'object' ? 
                    objectArray.push(list[peel[i]]): 
                    list[peel[i]] ? 
                        (list = list[peel[i]], objectPeeler()): null;
            }
        }
        objectPeeler();
        return objectArray;
    }

    But using the jquery .next method allows a better solution:

    function listToArray(list) {
      var array = [];
      for (var obj = list; obj; obj = obj.next)
        array.push(obj.value);
      return array;
    }

提交回复
热议问题