Home  >  Article  >  Web Front-end  >  JS defines parsing of variables concatenated with strings

JS defines parsing of variables concatenated with strings

coldplay.xixi
coldplay.xixiforward
2020-07-14 17:38:173928browse

JS defines parsing of variables concatenated with strings

I encountered a problem when writing js today. I have another page that needs to generate a lot of variables. But the names of variables are differentiated according to different parameters.

For example, you may need to generate date_1, date_2, datet_3... (the following numbers are based on parameters). So my function name should be generated by var name = "test_" num; But here comes the problem.

Related learning recommendations: javascript video tutorial

1 You can use window[name] = " " this way To define variables:

So var "test_" num = 100; This is definitely wrong. I found out later after asking my eldest brother. Variables can be defined using window[name] = 100. Look at the code

  function create_variable(num){
    var name = "test_"+num;  //生成函数名
    window[name] = 100;
    window['name'] = 200;  //注意看中括号里的内容加引号和不加引号的区别
  }
  create_variable(2);
  alert(test_2); // 100;
  alert(name); //200;

Summary

When window uses square brackets to define variables, the content in the square brackets should be a string. If it is a variable, he will parse the variable to find the specific value.

This is the difference between it and dot syntax. The content following dot syntax is the name of the variable to be defined. It will not analyze whether it is a variable or the like. For example

  var name = "test"
  window.name = 200
  alert(name); // 200
  alert(test);  ReferenceError: test is not defined

2 Use object form

var test = {};
  for(var i = 0; i < 3; i++){
    test[&#39;test_&#39;+i]=&#39;我是字符串&#39;+i;
 
    console.log(test[&#39;test_&#39;+i]); //输出:我是字符串0, 我是字符串1, 我是字符串2
  }
console.log(test_0); //输出:ReferenceError: test_0 is not defined
console.log(test[&#39;test_0&#39;]); //输出:我是字符串0

3 Use array form

var test = [];
  for(var i = 0; i < 3; i++){
    test[i]=&#39;我是字符串&#39;+i;
    console.log(test[i]); //输出:我是字符串0, 我是字符串1, 我是字符串2
  }
console.log(test[0]); //输出:我是字符串0

The above is the detailed content of JS defines parsing of variables concatenated with strings. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:jb51.net. If there is any infringement, please contact admin@php.cn delete