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

标签 javascript node.js

分割包含例如的字符串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/

相关文章:

javascript - 循环浏览 Canvas 图像以找到(几乎)纯色的最大点

mysql - 使用 Node.js 缓存数据库查询

node.js - 如何调试 "warning: Recursive process.nextTick detected. This will break in the next version of node."

javascript - 将对象推送到数组,该数组是数组 Mongoose 中对象的字段

node.js - 在 Yeoman 中使用 Node.js 的 module.exports 会产生不同的结果

javascript - NodeJS - 如何在现有元素中注入(inject)所有依赖项?

javascript - 从子组件reactjs更新状态

javascript - 无法将表单数据提取到 mongoDB

javascript - 排序映射,其中 value 是具有多个值的对象

JavaScript:如何从字符串数组中选择一个不太随机的元素。也就是说,某些元素应该更频繁地返回