Home > Web Front-end > JS Tutorial > body text

JS defines parsing of variables concatenated with strings

coldplay.xixi
Release: 2020-07-14 17:49:49
forward
3945 people have browsed it

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;
Copy after login

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
Copy after login

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
Copy after login

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
Copy after login

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!

Related labels:
source:jb51.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!