需要在javascript节点js中对此代码进行一些解释

时间:2019-05-07 15:15:02

标签: javascript node.js

分割包含例如5 5使用下面的代码,但是我不明白在此之后n将包含什么。

let [,n] = parsedInput[0].split(' ');
n = +n + 2;

1 个答案:

答案 0 :(得分:1)

// 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);

相关问题