分割包含例如的字符串5 5 具有以下代码,但我无法理解此后 n 将包含什么。
let [,n] = parsedInput[0].split(' ');
n = +n + 2;
最佳答案
// parsedInput is an array, we are getting the first element of it
// and split it considering the character space as the delimiter
// NOTE: we suppose that parsedInput[0] is a string
parsedInput[0].split(' ');
<小时/>
// The following syntax is called destructuring
let [,n]
//
// It's the equivalent of
const ret = parsedInput[0].split(' ');
let n = ret[1];
<小时/>
// The comma here means that we wants to ignore the first value, and only
// create a variable for the second one
let [,n]
// so obviously the goal here is to extract a word from a str
// example : str => 'word1 word2 word3'
// n will worth 'word2'
<小时/>
const parsedInput = [
'word1 word2 word3',
];
let [, n] = parsedInput[0].split(' ');
console.log(n);
// Then this line, is converting n to a number. So we suppose what we are
// looking for in the string is a number
// and then we add 2 to it
n = +n + 2;
// It's equivalent to
const number = Number(n) + 2;
const parsedInput = [
'word1 2 word3',
];
let [, n] = parsedInput[0].split(' ');
n = +n + 2;
console.log(n);
关于javascript - 需要在 javascript Node js 中对此代码进行一些解释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56025701/