简体   繁体   English

在函数外部填充数组不起作用

[英]Populating an array outside a function doesn't work

Here is a sample of what doesn't work: 以下是无效示例:

var array_one = [];
array_one=['a','b','c'];

Declaring and populating the array outside any function doesn't work, but 在任何函数外部声明和填充数组均无效,但是

var array_one = [];
function do_something(){
   array_one=['a','b','c'];
}

does, because it's inside a function. 这样做,因为它在函数内部。 Why? 为什么?

What you're doing here is not initialization but instead member lookup. 您在这里执行的不是初始化,而是成员查找。 The expression is parsed as array_one[<member name>] . 该表达式被解析为array_one[<member name>] In this case member_name is achieved by evaluating 'a', 'b', 'c' . 在这种情况下,member_name是通过评估'a', 'b', 'c' This uses the comma operator so the 3 expressions are evaluated in order and the result of the expression is the final expression: 'c' . 这使用逗号运算符,因此将按顺序评估3个表达式,并且表达式的结果是最终表达式: 'c' This means your code is effectively doing the following 这意味着您的代码正在有效地执行以下操作

array_one['c'];

It sounds like what you want is instead 听起来就像您想要的是

array_one = ['a', 'b', 'c'];

array_one['a','b','b'] is not syntax to populate an array - I'm not really sure what it does actually. array_one['a','b','b']不是填充数组的语法-我不太确定其实际作用。

If you do array_one = ['a','b','c'] then you replace the variable with a new array. 如果执行array_one = ['a','b','c']则用新数组替换变量。 (The difference between this and populating an array is that other references to the previous array will still have the old value.) (此数组与填充数组之间的区别在于,对先前数组的其他引用仍将具有旧值。)

To add values to the array, use array_one.push('a') . 要将值添加到数组,请使用array_one.push('a')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM