三元条件中的意外令牌中断 [英] unexpected token break in ternary conditional

查看:70
本文介绍了三元条件中的意外令牌中断的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面的函数旨在将(潜在嵌套的)对象的值作为数组返回-list参数为任何对象。如果将break语句移至for循环之后,则不会出现任何错误,但是当然,我的函数不会按照需要运行。我使用break的方式有什么问题?

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

推荐答案

万一其他人遇到这个问题:三元运算符只能使用值表达式,不能使用语句(例如break),并且不适用于这些情况。

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.

这有效:

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

但是使用jquery .next方法可以更好的解决方案:

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

这篇关于三元条件中的意外令牌中断的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆