javascript – 任何人都可以解释这个奇怪的JS行为关于字符串连接?

前端之家收集整理的这篇文章主要介绍了javascript – 任何人都可以解释这个奇怪的JS行为关于字符串连接?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我刚刚发布了一个要点: https://gist.github.com/2228570
var out = '';

function doWhat(){
    out += '<li>';
    console.log(out === '<li>'); // at this point,out will equal '<li>'
    return '';
}

out += doWhat();
console.log(out,out === '<li>');
// I expect out to == '<li>',but it's actually an empty string!?

这个行为是奇怪的,有没有人有解释?这是google的难处.如果你使用out =或out = out,它也没有区别.

编辑:@paislee做了一个JSFiddle,演示了如何做一个单独的行,它的行为如预期:http://jsfiddle.net/paislee/Y4WE8/

解决方法

看来你期待在评估=之前要调用doWhat.

但是,行的进展是:

out += doWhat();      // original line
out = out + doWhat(); // expand `+=`
out = '' + doWhat();  // evaluate `out`,which is currently an empty string
out = '' + '';        // call `doWhat`,which returns another empty string
out = '';             // result

out =’< li>‘;里面做什么更新变量,但太晚不能有持久的效果.

原文链接:https://www.f2er.com/js/155378.html

猜你在找的JavaScript相关文章