我是 Javascript 的初学者,遇到了这种语法用法(简化):
var testString ="firstName, lastName";
var [a,b] = testString.split(", ");
我的问题是变量 a 和 b 在第 2 行变成了什么类型?
我的简单调查似乎表明 a 和 b 被分配了各自的字符串值。
但幕后到底发生了什么?为什么我们在这里使用方括号[]? .split() 不是在过程中返回并创建了一个数组吗?否则,在后台创建了哪些对象?
理解 [a,b] 这种声明风格的链接也将受到欢迎。
但幕后到底发生了什么?
// You declare a string variable
var testString = "firstName, lastName";
// Split method help you to divide the string value according with the
//indicated separator, in this examle the comma
var [a,b] = testString.split(", ");
解构赋值语法是一个 JavaScript 表达式
使得可以从数组中解压值,或从
对象,转化为不同的变量。
自从split函数返回一个数组,其中var [a,b] = array
您按索引顺序分配值,在示例中:
console.log(a); // 'firstName'
console.log(b); // 'lastName'
它们是简单的字符串变量。您可能想访问以下链接:
解构指定 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment
分割功能 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split
更多资源:既然你提到你是从 JS 开始的,我建议你阅读这篇精彩文章中提到的书籍post https://medium.com/javascript-scene/12-books-every-javascript-developer-should-read-9da76157fb3
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)