如果我有一个字符串,
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);
(除了theValue
和theField
之外的变量没有在第一段代码中声明)
匹配非空格字符然后提取结果数组的第 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/