unexpected token break in ternary conditional

2020-05-06 17:21发布

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 after the for loop, I don't get any errors, but of course then my function doesn't behave as needed. What's wrong with the way I'm using break?

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

2条回答
我只想做你的唯一
2楼-- · 2020-05-06 17:46

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;
}

查看更多
相关推荐>>
3楼-- · 2020-05-06 17:56

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
查看更多
登录 后发表回答