开发者

Combining Strings without '+'

开发者 https://www.devze.com 2023-02-15 17:40 出处:网络
I come from python & if I want to print this line \"Hello World\" I can do this: line = \"Hello %s\" % \"World\"

I come from python & if I want to print this line "Hello World" I can do this:

line = "Hello %s" % "World"

How can I combine string templates with my variables like the above?

IE, I want to combine this

var arrray = new Array( "a", "b", "c" );
var template = "<option> %s </option>";

for ( var i in array )
{
    alert( template % i ); // should show "<option> 开发者_如何学Ca </option>" & so on
}


There's sprintf() for JavaScript.


Not addressing your root question, but a different (more flexible) approach to your example problem, using an MVVM framework:

<select data-bind="options: items"></select>

<script type="text/javascript">
    var viewModel = {
        items: ko.observableArray(["a", "b", "c"])
    };
    ko.applyBindings(viewModel);
</script>

This will accomplish all sorts of magical things, such as automatic/realtime binding, so when you add or remove elements from the array in the viewmodel, the <select> options automatically reflect that.

0

精彩评论

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