在 Javascript 中的多变量声明期间不熟悉方括号的使用 [英] Unfamiliar use of square brackets during multiple variable declaration in Javascript

查看:28
本文介绍了在 Javascript 中的多变量声明期间不熟悉方括号的使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Javascript 的初学者,遇到过这种语法用法(简化版):

var testString ="firstName, lastName";var [a,b] = testString.split(", ");

我的问题是什么类型的变量 a &b 然后变成第 2 行?
我的简单调查似乎表明 &b 被分配了各自的字符串值.

但是到底发生了什么?为什么我们在这里使用方括号 []?不是一个数组返回 &在过程中由 .split() 创建?否则,在后台创建了哪些对象?
也欢迎链接以了解 [a,b] 的这种声明风格.

解决方案

但是幕后发生了什么?

//你声明一个字符串变量var testString = "firstName, lastName";//Split 方法帮助您根据//指示分隔符,在本例中为逗号var [a,b] = testString.split(", ");

<块引用>

解构赋值语法是一个 JavaScript 表达式可以从数组中解压缩值,或从对象,变成不同的变量.

由于 split 函数返回一个数组,var [a,b] = array您正在按索引顺序分配值,在示例中:

console.log(a);//'名'控制台日志(b);//'姓'

它们是简单的字符串变量.您可能想查看以下链接:

解构赋值

拆分函数

更多资源:既然你提到你是从 JS 开始的,我建议你阅读这篇巨著中提到的书籍 post

I'm a beginner to Javascript and encountered this syntax usage(simplified):

var testString ="firstName, lastName";
var [a,b] = testString.split(", ");

My question is what typeof variable a & b then becomes at line2?
My simplistic investigation seems to indicate a & b are assigned respective string values.

But what goes on under the hood? why do we use square brackets [] here? Isn't an array returned & created in the process by .split()? Otherwise, what objects were created in the background?
Links to understand this style of declaration for [a,b] would also be welcomed.

解决方案

But what goes on under the hood?

// 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(", ");

The destructuring assignment syntax is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables.

Since the split function returns an array, with the var [a,b] = array you are assigning the value in index order, in the example:

console.log(a); // 'firstName'
console.log(b); // 'lastName'

And they are simple string variables. You may want to vist the links below:

Destructuring asignation

split function

Further resources: Since you have mentioned you are beginning with JS, I suggest you to read books mentioned in this magnific post

这篇关于在 Javascript 中的多变量声明期间不熟悉方括号的使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆