【问题标题】:Plus removed other parts of string and keeps only the matching加上删除字符串的其他部分,只保留匹配
【发布时间】:2018-04-23 02:33:35
【问题描述】:

这是我的代码:

const prepD = {
            name: 'John Smith',
            objArr: [
                'test',
                'Lorem ipsum ' + check() ? 'true' : 'false' + ' rest of text'
            ]
        };

在我的情况下,当check() 返回true 我只得到这个输出:

true,而我应该得到Lorem Ipsum true rest of text

如果语句为true,为什么要删除剩余的拼接文本以及如何保留全文?

谢谢/

【问题讨论】:

    标签: javascript html reactjs ecmascript-6 jsx


    【解决方案1】:

    您应该使用() 包装条件以将其转换为表达式:

    (check() ? 'true' : 'false')
    

    运行示例:

    function check(){return true;}
    const prepD = {
      name: 'John Smith',
      objArr: [
        'test',
        'Lorem ipsum ' + (check() ? 'true' : 'false') + ' rest of text'
      ]
    };
    
    console.log(prepD.objArr);

    【讨论】:

    • 嗨,是的,我已经尝试过了。'Lorem ipsum ' + (check() ? 'true' : 'false') + ' rest of text' 出于某种原因给了我“错误”,尽管它应该是 true。因此,出于某种原因,它验证了第二个陈述为真..
    • 确保check 然后返回true。正如您在我发布的 sn-p 中看到的那样,它按预期运行。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-18
    • 2022-11-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多