unexpected token break in ternary conditional

假如想象 提交于 2019-12-02 19:16:32

问题


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

回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/37092513/unexpected-token-break-in-ternary-conditional

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!