如何将变量分配给具有特定索引的拆分字符串?

3
如果我有一个字符串,
const string = 'This is a value and this is a field'

在将字符串拆分后,如何对术语value和术语field进行解构?

类似于以下方式:

const [theValue, theField] = string.split(" ")[3][8]

这可行吗?

1个回答

4

如果你想使用解构,虽然可以实现,但我不建议这样做,因为它看起来会非常混乱:

const string = 'This is a value and this is a field'
const [,,,theValue,,,,, theField] = string.split(" ");
console.log(theValue, theField);

这是可能的,因为在解构可迭代对象时,列出值是可选的。同样,您可以执行以下操作:
const [, one] = [0, 1]

将数字 1 存入名为 one 的变量中。
去糖后,第一行代码等同于:

const string = 'This is a value and this is a field'
const splits = string.split(" ");
const [
  firstWord,
  secondWord,
  thirdWord,
  theValue,
  fifthWord,
  sixthWord,
  seventhWord,
  eighthWord,
  theField
] = string.split(" ");
console.log(theValue, theField);

(除了变量theValuetheField在第一段代码中没有声明之外)

更合理的做法是匹配非空格字符,然后提取结果数组的第三个和第八个索引:

const string = 'This is a value and this is a field';
const words = string.match(/\S+/g);
const theValue = words[3];
const theField = words[8];
console.log(theValue, theField);

使用\S+匹配非空格字符而不是在空格上分割,将会有更可靠的结果 - 在使用.split时,当存在任何前导或尾随空白时,可能会导致空字符串前导或尾随。

1
CertainPerformance 总是火力全开。谢谢,这对我来说只会更加混乱,因为只有我的眼睛能看到这段代码 :) - Mike K
那个 ,,, 在 theValue 前面以及 ,,,,,theField 前面的逻辑是什么? - Prashant Pimpale
@CertainPerformance 谢谢,但是你可以看到为了得到第四个值,你使用了三个逗号“,,,”,但在那之后只有4个单词直到最后一个值,那么为什么要使用五个逗号“,,,,,”来获取最后一个项目?或者它会忽略已经取出的单词吗?这意味着它没有计算theValue,是吗? - Prashant Pimpale
是的,我理解了!这就是为什么它需要计算 theValue - Prashant Pimpale
@PrashantPimpale 在JavaScript中,索引从0开始 :) - Mike K
@MikeK 是的,我很清楚!我认为如果你从数组中destruct一个单词,它会自己计算一个项目,这样你就可以使用下一个索引来访问下一个单词。但是这里并非如此,你只需解构并忽略,并从该索引开始获取下一个值! - Prashant Pimpale

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接