javascript - 动态传递父对象作为 JavaScript 中的参数

标签 javascript object javascript-objects

这是我在论坛中的第一个问题。在问你们之前我已经搜索了很多,但也许是因为我仍在培养我的 JavaScript 技能,所以我无法弄清楚。

我正在尝试根据如下所示的 URL 动态传递一个对象作为参数。

 let createDataLayer = () => {

  //Creating objects with the values for each page
  someurl = {
    pageType: 'Content',
    institution: 'Institution',
    contentTopic: 'Membership',
    productCategory: '',
    productName: '',
  };

  //Attaching the right array to the actual url
  let actualURL = "/some-url/";
  actualURL = actualURL.replace(/-/g,"");
  actualURL = actualURL.replace(/\//g,"");

  //Function that applies the right content to the right page
  let applyingContent = (variable) => {
    console.log("Always come as string: ", typeof variable); //string
    console.log("Can't access the object: ", variable.pageType); //undefined
    console.log("If I call the variable itself, it's here: ", someurl); //the object logs ok
    window.dataLayerValues = [variable.pageType, variable.institution, variable.contentTopic, variable.productCategory, variable.productName];
    return window.dataLayerValues;
  }

  applyingContent(actualURL);

}
createDataLayer();

谁能帮帮我吗?

非常感谢!

最佳答案

通过其他变量中保存的字符串访问变量并不是 JavaScript 中通常完成的事情。您的代码通常不应该关心变量的名称。如果您需要组织数据以便可以使用字符串键访问它,则应该使用具有与字符串对应的键的对象。看起来像这样:

const urls = {
    someurl: {
        pageType: 'Content',
        institution: 'Institution',
        contentTopic: 'Membership',
        productCategory: '',
        productName: '',
    }
}

然后,您可以使用 urls[key] 访问数据,其中 key 是您的字符串。

然后您只需对代码进行一些更改即可使用它:

let createDataLayer = () => {

    //Creating objects with the values for each page
    const urls = {
        someurl: {
            pageType: 'Content',
            institution: 'Institution',
            contentTopic: 'Membership',
            productCategory: '',
            productName: '',
            }
        }
  
    //Attaching the right array to the actual url
    let actualURL = "/some-url/";
    actualURL = actualURL.replace(/-/g,"");
    actualURL = actualURL.replace(/\//g,"");
  
    //Function that applies the right content to the right page
    let applyingContent = (variable) => {
      console.log("Strill a string: ", typeof variable); //string
      // object accessed with key: urls[variable]
      console.log("Can access the object: ", urls[variable].pageType); //undefined
      return  urls[variable];
    }
  
    applyingContent(actualURL);
  
  }
  createDataLayer();

这会将所有数据整齐地打包在一个对象中,而不是让各个变量遍布各处。您可以传递该对象、更改它等等。

关于javascript - 动态传递父对象作为 JavaScript 中的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53023034/

相关文章:

javascript - NodeJS断言.AssertionError : How do I kill it?

java - 当类名已知时,将 Object 类的 java 对象动态转换为给定的类

java - 如何将这些分数相加得出最终值?

Javascript:像搜索查询字符串一样解析数组

javascript - 如何使用 react 导航?

javascript - 提取并添加指向字符串中 URL 的链接

Javascript 显示所有包含匹配字符串的对象

Javascript 扩展内置类

javascript - 以数组为参数的 Java 和 Javascript 绑定(bind)函数

C++:堆栈不会在抛出异常时展开