开发者

How to add two or more variables in jQuery ( mirror of .= operator in PHP)

Sorry i am so new to jQuery and not sure how to do that.

Basically in php i can do something like this:

$result = '';
$result .= 'Hi';
$result .= ' there';
echo $result;

I am just asking if there's an exact copy or alternative in jQu开发者_如何学Goery. instead of adding variables with plus sign which works for me, but I want all variables to be added up to the large variable, just i do in php.

Thanks very much.


var result = '';
result += 'Hi';
result += ' there';
document.write(result);

Note this is just plain javascript, not jquery


As others have mentioned, yes, + is used for concatenation, but is the equivalent of . in PHP. The direct equivalent of .= in JavaScript is +=

var $result = '';
$result += 'Hi';
$result += ' there';
alert($result);


Your friend is the dual purpose + operator.

Though it won't be your friend for long when you realise overloading the addition operator for string concatenation can bite you bad in a dynamically typed language.

There is also a jQuery plugin (seeing as you tagged it jQuery) :P.

jQuery.strcat = function() {  
    return Array.prototype.slice.call(arguments).join();
};

alert($.strcat('a', 'b', 'c'));


You can use the + operator for string concatenation, as described above.

Worth mentioning is another way to do this. Put the items into an array, and use the join method. This is common in Python and other language.

result=[];
result.push('Hi');
result.push('there');
result.join(' ');


In Javascript, the concatenation operator is '+':

var str = 'Hello' + ' ' + 'Fred';
alert(str);

You can't interpolate variables in a double-quoted string, as you can with PHP (which is one of the purposes of PHP's dollar ($) sigil). You have to use concatenation:

var anotherStr = str + ', what day is it?';
// or
str += ', what day is it?';
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜