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

标签 javascript

如果我有一个字符串,

const string = 'This is a value and this is a field'

如何在拆分字符串后解构术语value和术语field

有点像,

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

这可能吗?

最佳答案

如果你打算使用解构,这是可能的,但我不推荐它,它看起来真的令人困惑:

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之外的变量没有在第一段代码中声明)

匹配非空格字符然后提取结果数组的第 3 和第 8 个索引会更明智:

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 可以导致空字符串开头或结尾当有任何前导或尾随空格时)

关于javascript - 如何将变量分配给具有特定索引的拆分字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59853810/

相关文章:

javascript - 连接两个 JSON 对象

javascript - Blogger 上的 JQuery 文档加载问题

javascript - AJAX:异步将文件发布到服务器

javascript - 在 ES6 中修改新请求对象的 URL

javascript - 一旦 Javascript 中任何 HTML 元素的值发生变化,就更新 Canvas

javascript - 如何衡量一个网页何时完成2个功能?

javascript - token 输入无法访问 ASP.Net Web 方法

javascript - 如何从二维数组中提取列?

javascript - 向特定用户广播事件(socket.io、redis、node)

javascript - 如何替换html5中的输出文本框?