我正在传递一个JavaScript变量,该变量包含地址,并且在一个句子中包含多个字符串。因此,在设置变量时,我想将句子分为两行,即streetNumber和streetName应该在第一行中,city和邮政编码在第二行中。因此,我尝试使用<br>
标签来打断行,如下所示:
let addr2 = inputDataState.addressDetails.addrObj.street.streetNumber + ' '
+ inputDataState.addressDetails.addrObj.street.streetPrefixCode
+ inputDataState.addressDetails.addrObj.street.streetName+ ' ' + <br />
+ inputDataState.addressDetails.addrObj.street.streetSuffixCode + ' '
+ inputDataState.addressDetails.addrObj.street.city + ' '
+ inputDataState.addressDetails.addrObj.street.zipCode ;
但是我得到[object Object]
而不是换行符。那么如何添加换行符以将变量分为两行?
答案 0 :(得分:0)
在要打印的变量中插入“ \ n”。
示例
let streetName ='Madhapur, Hyderabad \n India-500081';
console.log(streetName );
将像下面这样打印
Madhapur, Hyderabad
India-500081
只需在要换行的位置添加'\ n'。
let addr2 = inputDataState.addressDetails.addrObj.street.streetNumber + ''
+ inputDataState.addressDetails.addrObj.street.streetPrefixCode
+ inputDataState.addressDetails.addrObj.street.streetName+ '\n ' +
+ inputDataState.addressDetails.addrObj.street.streetSuffixCode + ' '
+ inputDataState.addressDetails.addrObj.street.city + ' '
+ inputDataState.addressDetails.addrObj.street.zipCode ;
答案 1 :(得分:0)
第一个是换行符(\ n)。换行符可以在字符串输出中创建换行符,无论是文本还是JavaScript生成的HTML。
inputDataState.addressDetails.addrObj.street.streetNumber + ' '
+ inputDataState.addressDetails.addrObj.street.streetPrefixCode
+ inputDataState.addressDetails.addrObj.street.streetName+ ' ' + '\n'
+ inputDataState.addressDetails.addrObj.street.streetSuffixCode + ' '
+ inputDataState.addressDetails.addrObj.street.city + ' '
+ inputDataState.addressDetails.addrObj.street.zipCode ;
答案 2 :(得分:0)
使用另一个变量,这样您就不必键入太多内容并用Template Literals进行内插
let inputDataState = {
addressDetails: {
addrObj: {
street: {
streetNumber: '123',
streetPrefixCode: 'S.',
streetName: 'Main',
streetSuffixCode: 'St.',
city: 'Springfield',
zipCode: '95123'
}
}
}
};
const x = inputDataState.addressDetails.addrObj.street;
let addr = `${x.streetNumber}
${x.streetPrefixCode}
${x.streetName}
${x.streetSuffixCode}
${x.city}
${x.zipCode}`;
console.log(addr);
答案 3 :(得分:0)
您应该使用Object_destructuring和Template_literals来解决问题,并使代码更简洁
const {
streetNumber,
streetPrefixCode ,
streetName,
streetSuffixCode,
city,
zipCode
} = inputDataState.addressDetails.addrObj.street
let addr2 = `${streetNumber} ${streetPrefixCode} ${streetSuffixCode}
${streetSuffixCode} ${city} ${zipCode}`
对此进行测试
console.log(`${6+2}
is
equal
to
${2*4}`)