简体   繁体   English

在JavaScript中将字符串转换为数组名称

[英]converting string to array name in JavaScript

my Goal is to be able to create a function that you can give a string as an argument, and be able to make an array that I could add Items to. 我的目标是能够创建一个函数,该函数可以将字符串作为参数,并能够创建可以向其中添加Items的数组。 You can see my attempt here, but it doesn't seem to work. 您可以在这里看到我的尝试,但是似乎没有用。 aka, if I want to make a list name GroceryList, it returns GroceryList, but when I want to add an item to it, it says GroceryList is not defined. aka,如果我想创建一个列表名称GroceryList,它返回GroceryList,但是当我想向其中添加一个项目时,它说GroceryList没有定义。

function removeInstance(list, item){
  for(var i = 0; i < list.length; i++){
    if(item === list[i]){
      list.splice(i, 1);
      console.log(list);
      break;
    }
  }
}
function makeList(name){
  name = [];
  console.log(name);
  return name;
}
function removeAllItems(list, item){
  for(var i = 0; i < list.length; i++){
    if(item === list[i]){
      list.splice(i, 1);
      i--;
    }
  }
  console.log(list);
}
function addItem(list, item){
    list.push(item);
    console.log(list);
}

any help would be awesome. 任何帮助都是极好的。 Thanks! 谢谢!

Parameters in JavaScript functions are passed by value, not reference; JavaScript函数中的参数是通过值而不是引用传递的; therefore, when you do something like this 因此,当你做这样的事情时

var foo = 'bar';

function makeList(name){
  name = [];
  console.log(name);
  return name;
}

makeList(foo);
console.log(foo); // shows 'bar'

you are not modifying the variable which was declared outside the function. 您没有修改在函数外部声明的变量。 Changes to a parameter only affect that local function and not the original variable. 对参数的更改只会影响该局部函数,而不会影响原始变量。

At any rate, I cannot think of any possible scenario where you would need such a makeList function. 无论如何,我想不出任何需要这种makeList函数的情况。 If you need an array, just create one - there is no need for this! 如果您需要一个数组,则只需创建一个-无需这样做!

You need a scope in which you create this array. 您需要在其中创建此数组的作用域。 Suppose you put the JavaScript in an HTML page and you want the array to be in the global scope, then you can create the array as a property of the window object: 假设您将JavaScript放在HTML页面中,并且希望数组位于全局范围内,那么您可以将数组创建为window对象的属性:

function makeList(name){
   window[name] = [];
   return window[name];
}

You can use it like this: 您可以像这样使用它:

    var arr = makeList("myList");
    myList.push("hello");
    alert('item 0 = ' + myList[0]);

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

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