Javascript 变量声明语法

Javascript variable declaration syntax

本文关键字:语法 声明 变量 Javascript      更新时间:2023-09-26

我正在负责一个javascript webapp。它非常复杂,我在语法方面遇到了一些问题:

getThemeBaseUrl = function() {
  var customConfigPath = "./customer-configuration";                    
  if (parseQueryString().CustomConfigPath) {                           
    customConfigPath = parseQueryString().CustomConfigPath;
  }
  var clientId = parseQueryString().ClientId; 
  return customConfigPath + "/themes/" + clientId;
};
parseQueryString = function() {
  var result = {}, queryString = location.search.substring(1), re = /([^&=]+)=([^&]*)/g, m;
  while ( m = re.exec(queryString)) {
    result[decodeURIComponent(m[1])] = decodeURIComponent(m[2]);
  }
  return result;
};

特别是parseQueryString().CustomConfigPathvar result = {}, queryString = location.search.substring(1), re = /([^&=]+)=([^&]*)/g, m;

第一个似乎是parseQueryString函数的一种属性访问。

第二个似乎是数组声明,但没有 Array() 构造函数。此外,m值被调用,而假定的数组结果不会在 while 循环中出现。

通过查看:

parseQueryString().CustomConfigPath

可以说parseQueryString()应该返回一个具有CustomConfigPath属性的对象。

由此:

var result = {};

你可以看到result确实是一个对象({}是一个空对象文字)。它不是一个数组。稍后,在一个循环中,有:

result[decodeURIComponent(m[1])] = decodeURIComponent(m[2]);

因此,我们将属性分配给result对象。此属性之一将是(正如我们可以预期的那样)一个 CustomConfigPath .这将取自查询字符串 - 我们将使用正则表达式来执行此操作:re = /([^&=]+)=([^&]*)/g .因此,执行此代码的网页的地址如下所示:http://example.com/something?SomeKey=value&CustomConfigPath=something

为对象分配属性的一般语法为:

result[key] = value;
// key   -> decodeURIComponent(m[1]) 
// value -> decodeURIComponent(m[2])

parseQueryString().CustomConfigPath调用返回对象的parseQueryString函数。然后,它访问该对象的 CustomConfigPath 属性。函数前 4 行的常见习惯用语是:

var customConfigPath = parseQueryString().CustomConfigPath || "/.customer-configuration";

var result = {}, queryString = location.search.substring(1), re = /([^&=]+)=([^&]*)/g, m 是 4 个不同变量的声明,而不是数组:

  • result是一个空对象
  • queryString是当前 URL 中的查询字符串,删除?
  • re是正则表达式
  • m是未初始化的变量,它将在稍后的while循环中分配。