unexpected token break in ternary conditional

前端 未结 2 1796
别跟我提以往
别跟我提以往 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;
    }

    0 讨论(0)
  • 2021-01-27 05:41

    why not writing something like this :

    var obj = { 0: "a", 1: "b", 2: "c"}; //test target
    var objectArray = [];
    var keyArray = Object.getOwnPropertyNames(obj);
    for (var i = 0; i < keyArray.length; i++)  objectArray.push(obj[keyArray[i]]);
    console.log(objectArray);  // test result
    
    0 讨论(0)
提交回复
热议问题