在 JavaScript 中声明多个变量

发布于 2024-09-30 12:21:39 字数 315 浏览 5 评论 0原文

我想在一个函数中声明多个变量:

function foo() {
    var src_arr     = new Array();
    var caption_arr = new Array();
    var fav_arr     = new Array();
    var hidden_arr  = new Array();
}

这是正确的方法吗?

var src_arr = caption_arr = fav_arr = hidden_arr = new Array();

I want to declare multiple variables in a function:

function foo() {
    var src_arr     = new Array();
    var caption_arr = new Array();
    var fav_arr     = new Array();
    var hidden_arr  = new Array();
}

Is this the correct way to do this?

var src_arr = caption_arr = fav_arr = hidden_arr = new Array();

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

屋檐 2024-10-07 12:21:39

是的,如果您希望它们全部指向内存中的同一个对象,但很可能您希望它们是单独的数组,这样如果一个数组发生变化,其他数组就不会受到影响。

如果您不希望它们全部指向同一个对象,请执行

var one = [], two = [];

[] 是用于创建数组的简写文字。

下面的控制台日志表明了差异:

>> one = two = [];
[]
>> one.push(1)
1
>> one
[1]
>> two
[1]
>> one = [], two = [];
[]
>> one.push(1)
1
>> one
[1]
>> two
[]

在第一部分中,我定义了 onetwo 来指向内存中的相同对象/数组。如果我使用 .push 方法,它将 1 推送到数组,因此 onetwo 都有 1里面。自从我为每个变量定义了唯一的数组以来,第二个数组中,当我推到一个时,两个不受影响。

Yes, it is if you want them all to point to the same object in memory, but most likely you want them to be individual arrays so that if one mutates, the others are not affected.

If you do not want them all to point to the same object, do

var one = [], two = [];

The [] is a shorthand literal for creating an array.

Here's a console log which indicates the difference:

>> one = two = [];
[]
>> one.push(1)
1
>> one
[1]
>> two
[1]
>> one = [], two = [];
[]
>> one.push(1)
1
>> one
[1]
>> two
[]

In the first portion, I defined one and two to point to the same object/array in memory. If I use the .push method it pushes 1 to the array, and so both one and two have 1 inside. In the second since I defined unique arrays per variable so when I pushed to one, two was unaffected.

别把无礼当个性 2024-10-07 12:21:39

远离这种赋值模式,即使您想让所有变量都指向同一个对象。

事实上,只有第一个是变量声明,其余的只是对可能未声明的标识符的赋值!

强烈建议不要为未声明的标识符赋值(又名未声明的赋值),因为如果在作用域链上找不到该标识符,则会创建一个 GLOBAL 变量。例如:

function test() {
    // We intend these to be local variables of 'test'.
    var foo = bar = baz = xxx = 5;
    typeof foo; // "number", while inside 'test'.
}
test();

// Testing in the global scope. test's variables no longer exist.
typeof foo; // "undefined", As desired, but,
typeof bar; // "number", BAD!, leaked to the global scope.
typeof baz; // "number"
typeof xxx; // "number"

此外,ECMAScript 第 5 严格模式不允许这种分配。
在严格模式下,对未声明的标识符进行赋值将导致 TypeError 异常,以防止隐含的全局变量。

相比之下,如果编写正确的话,我们会看到以下内容:

function test() {
    // We correctly declare these to be local variables inside 'test'.
    var foo, bar, baz, xxx;
    foo = bar = baz = xxx = 5;
}
test();

// Testing in the global scope. test's variables no longer exist.
typeof foo; // "undefined"
typeof bar; // "undefined"
typeof baz; // "undefined"
typeof xxx; // "undefined"

Please stay away from that assignment pattern, even if you wanted to have all variables pointing to the same object.

In fact, only the first one will be a variable declaration, the rest are just assignments to possibly undeclared identifiers!

Assigning a value to an undeclared identifier (aka undeclared assignment) is strongly discouraged because, if the identifier is not found on the scope chain, a GLOBAL variable will be created. For example:

function test() {
    // We intend these to be local variables of 'test'.
    var foo = bar = baz = xxx = 5;
    typeof foo; // "number", while inside 'test'.
}
test();

// Testing in the global scope. test's variables no longer exist.
typeof foo; // "undefined", As desired, but,
typeof bar; // "number", BAD!, leaked to the global scope.
typeof baz; // "number"
typeof xxx; // "number"

Moreover, the ECMAScript 5th Strict Mode, disallows this kind of assignments.
Under strict mode an assignment made to a non-declared identifier will cause a TypeError exception, to prevent implied globals.

By contrast, here is what we see if written correctly:

function test() {
    // We correctly declare these to be local variables inside 'test'.
    var foo, bar, baz, xxx;
    foo = bar = baz = xxx = 5;
}
test();

// Testing in the global scope. test's variables no longer exist.
typeof foo; // "undefined"
typeof bar; // "undefined"
typeof baz; // "undefined"
typeof xxx; // "undefined"
爱要勇敢去追 2024-10-07 12:21:39

不,您的第二条语句将创建对同一数组的四个引用。你想要:

var src_arr     = [],
    caption_arr = [],
    fav_arr     = [],
    hidden_arr  = [];

No, your second statement will create four references to the same array. You want:

var src_arr     = [],
    caption_arr = [],
    fav_arr     = [],
    hidden_arr  = [];
枫以 2024-10-07 12:21:39

所有这些变量都将引用一个 Array 对象。

All those variables will refer to one Array object.

z祗昰~ 2024-10-07 12:21:39

出于所有意图和目的,应使用文字[]表示法语法。由于数组构造函数在如何处理其参数方面是不明确的。

来自文档:< /a>

如果传递给数组构造函数的唯一参数是整数
介于 0 和 232-1(含)之间,这将返回一个新的 JavaScript 数组
其 length 属性设置为该数字。这意味着带有未定义值的空槽的传递长度数组

new Array(1, 2, 3); // Result: [1, 2, 3]
new Array(3); // Result: [empty × 3] with undefined at indexes
new Array('3') // Result: ['3']

//this was ambiguous
let x = new Array(5); // Result: [empty × 5]
x.push("Hello"); //expected x as ["Hello", empty, empty, empty, empty]
//Actual x: [empty × 5, "Hello"]

解构语法:

声明多个变量的另一种更简洁的方法是使用 解构赋值,它可以将数组中的值或对象中的属性解包到不同的变量中。

function foo() {
  //destructuring assignment syntax
  let [src_arr, caption_arr, fav_arr, hidden_arr] = [[], [], [], []];

  console.info("Variables::", fav_arr, hidden_arr, caption_arr, src_arr);

  fav_arr.push("fav");
  hidden_arr.push("hidden");

  //After adding some values to couple of arrays
  console.info("Variables::", fav_arr, hidden_arr, caption_arr, src_arr);
}

foo();

For all intents and purposes the literal [] notation syntax should be used. Since the Array constructor is ambiguous in how it deals with its parameters.

From the docs:

If the only argument passed to the Array constructor is an integer
between 0 and 232-1 (inclusive), this returns a new JavaScript array
with its length property set to that number. And that implies Array of passed length of empty slots with undefined values.

new Array(1, 2, 3); // Result: [1, 2, 3]
new Array(3); // Result: [empty × 3] with undefined at indexes
new Array('3') // Result: ['3']

//this was ambiguous
let x = new Array(5); // Result: [empty × 5]
x.push("Hello"); //expected x as ["Hello", empty, empty, empty, empty]
//Actual x: [empty × 5, "Hello"]

Destructuring syntax:

Another neater way to declare multiple variables is using destructuring assignment which enables unpacking values from arrays, or properties from objects, into distinct variables.

function foo() {
  //destructuring assignment syntax
  let [src_arr, caption_arr, fav_arr, hidden_arr] = [[], [], [], []];

  console.info("Variables::", fav_arr, hidden_arr, caption_arr, src_arr);

  fav_arr.push("fav");
  hidden_arr.push("hidden");

  //After adding some values to couple of arrays
  console.info("Variables::", fav_arr, hidden_arr, caption_arr, src_arr);
}

foo();

桃酥萝莉 2024-10-07 12:21:39

实际上有更短的方法可以使用 JavaScript 声明多个变量。首先,您只能使用一个变量关键字(var、let 或 const)并声明变量名称和值,并用逗号分隔。

const Sam="10yr", Joe="30yr", Bob="15yr", Mary="21yr";

there are actually shorter ways to declare multiple variables using JavaScript. First, you can use only one variable keyword (var, let, or const) and declare the variable names and values separated by commas.

const Sam="10yr", Joe="30yr", Bob="15yr", Mary="21yr";
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文