我已将输入读取为字符串,并将其拆分后,该字符串变成了一个对象。
process.stdin.resume();
process.stdin.setEncoding('utf8');
process.stdin.on('data',(c)=>{
in += c;
});
process.stdin.on('end',()=>{
spliter(in);
});
function spliter(in){
console.log(typeof(in));
in = in.split('\n');
console.log(typeof(in));
}
最佳答案
您的代码不会改变字符串。
字符串(以及其他基本类型)在 JS 中是不可变的。
改变某些东西意味着改变它而不创建另一个。
字符串修饰符方法返回一个新字符串,但不会更改原始字符串,例如:
const a = 'Hello world!'
const b = a.slice(0,5)
console.log(a) //Hello world!
console.log(b) //Hello
但是,您仍然可以使用新字符串重新分配字符串变量(但这不是突变):
let a = 'Hello world!'
a = a.slice(0,5)
console.log(a) //Hello
你的代码有点复杂。 String#split()
返回一个字符串数组,但不会改变原始字符串:
const a = 'Hello world!'
const b = a.split('o')
console.log(a) //Hello world!
console.log(b) //['Hell', ' w', 'rld!']
数组(事实上)是对象,并且它们是可变的,但它们包含的字符串(和其他基元)则不然。
关于javascript - 如果 JavaScript 中的字符串是不可变的,为什么下面的代码会改变字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59341879/