[英]How do I render a variable in a URL path in JavaScript?
I have the following line: 我有以下几行:
var myCustomVariable = '3434';
urlpath = '/people/myCustomVariable/folders/byid/'
I want to render the value of myCustomVariable in the urlpath but being new to JS I am unable to figure this out. 我想在urlpath中呈现myCustomVariable的值,但是对于JS来说是新手,所以我无法弄清楚。 I tried doing the following but didn't work:
我尝试执行以下操作,但不起作用:
"+myCustomVariable+"!"
What am I doing wrong? 我究竟做错了什么?
You use the +
operator: 您使用
+
运算符:
var myCustomVariable = '3434';
urlpath = '/people/' + myCustomVariable + '/folders/byid/'
This is called "concatenation" or (because we're dealing with strings) "string concatenation." 这称为“串联”或(因为我们正在处理字符串)“字符串串联”。
Your "I tried doing the following..." uses double quotes and a !
您的“我尝试执行以下操作...”使用双引号和一个
!
. 。 I'm not sure where the
!
我不确定在哪里
!
comes from, but in JavaScript, if you open a string with a single quote, you must end it with a single quote; 来源,但是在JavaScript中,如果用单引号打开字符串,则必须以单引号结尾; and if you open it with a double quote, you must end it with a double quote.
如果用双引号将其打开,则必须用双引号将其结束。
Just do the concatenation of strings like this: 只需执行以下字符串的串联操作:
var myCustomVariable = '3434';
urlpath = '/people/' + myCustomVariable + '/folders/byid/'
When you do this: 执行此操作时:
"+myCustomVariable+"
That represents a string, not your variable. 那代表一个字符串,而不是你的变量。 Your variable is
您的变量是
myCustomVariable
Without the "
aroud it 没有
"
See this: 看到这个:
var myCustomVariable = '3434';
//This
urlpath = '/people/' + myCustomVariable + '/folders/byid/'
//Same than
urlpath = '/people/' + '3434' + '/folders/byid/'
//Same than
urlpath = '/people/3434/folders/byid/'
But 但
var myCustomVariable = '3434';
//This
urlpath = '/people/' + '+myCustomVariable+' + '/folders/byid/'
//Same than
urlpath = '/people/+myCustomVariable+/folders/byid/'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.