dongzha0813 2016-07-20 23:16
浏览 227
已采纳

Javascript / Jquery - 如何根据变量设置变量名称

This has been asked a bunch of times before but I'm not grasping it.

In the following..

var variableName = "hello";

How do I make the variable name 'variableName' based on another variable?

PHP Example

$a = 'hello';
$$a = 'hi'; // same as $hello..
echo $hello; // and $hello outputs 'hi'

I specifically need this variable variable to be used for localstorage so it may be syntax that I'm having a problem with.


What I'm Using It For (you can probbaly skip to This Seems To Work)


I want to generate a unique variable name for storing information in local storage. Variable name will be based on the post id of the wordpress post/page which I retrieve with php.

For example we will say the post id is 3333

I add the letters id to the beginning of each post id

So now I have id3333

var postIdNumber = 'id3333';

Then I get 3 other pieces of information that I want to store into local storage about this post (for simplicity I have shown an example output, not the code to get it)

var postURL = 'website.comm/a-wp-post/';
var postTitle = 'A Wordpress Post';
var postThumb = 'website.comm/images/thumb3333.jpg';

Now I want to store this information into local storage

var lsTest = { 'lsURL': postURL, 'lsTitle': postTitle, 'lsThumb': postThumb };
localStorage.setItem('lsTest', JSON.stringify(lsTest));

That works fine. Except that I want to be able to store multiple posts into local storage to retrieve later from a 'my favourite posts' page.

So I need a dynamic variable name.

  • For post ID 3333 I need the variable currently named lsTest to be named id3333
  • For post ID 4444 I need the variable currently named lsTest to be named id4444

This seems to work (Though I dont fully comprehend it) solution modified from https://stackoverflow.com/a/5187652/3377049

var variableVariable = {}
variableVariable.postNumber = 'id3333';
var vv = 'postNumber';
jQuery('.test-div').text(variableVariable[vv]); // outputs id3333

While this does not..

var variableVariable = {} // also, should this have a ';' ?
variableVariable.postNumber = 'id3333';
var vv = 'postNumber';
var variableVariable[vv] = { 'lsURL': postURL, 'lsTitle': postTitle, 'lsThumb': postThumb };
localStorage.setItem('variableVariable[vv]', JSON.stringify(variableVariable[vv]));

In PHP I could maybe do something like this.. (for examples sake i'm mixing php variables into JS)

$uv = 'id3333';
$$uv = { 'lsURL': postURL, 'lsTitle': postTitle, 'lsThumb': postThumb };
localStorage.setItem('$$uv', JSON.stringify($$uv));
  • 写回答

2条回答 默认 最新

  • du90093662774150 2016-07-20 23:28
    关注

    Variable variables are not a good idea even in PHP. Just make an array or a hash (which is an object, but it's used as a hash or map, where you can add and delete properties or entries as you please).

    var posts = {};
    var someId = 3333; //or '3333' if it isn't a number
    
    posts[someId] = {
      URL: postURL,
      title: postTitle,
      thumb: postThumb
    };
    
    localStorage.setItem('post' + someId, JSON.stringify(posts[someId]));
    

    A property named "foo" on an object named "bar" can be accessed like so:

    bar.foo = 'baz';
    console.log(bar.foo);
    

    or like so:

    bar['foo'] = 'baz';
    console.log(bar['foo']);
    

    Which is the same as:

    var name = 'foo';
    bar[name] = 'baz';
    console.log(bar[name]);
    

    Finally, the global object in JavaScript (which in the browser is window) "holds" the global variables.

    var myGlobal = 10;
    console.log(window.myGlobal); // logs 10
    var globalName = 'foo';
    window[globalName] = 'baz';
    console.log(foo); //logs 'baz'
    

    Using global variables in general is discouraged. Using them to store posts where the name of the var is the id is highly unorthodox and many JS developers would consider it simply wrong.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看