duanlie4621 2013-09-16 15:30
浏览 168
已采纳

(节点)js中的“关联数组”数组

I have this code in php to translate in js (node to be precise)

$config['test'] = array(
     "something" => "http://something.com/web/stats_data2.php"
    ,"somethingelse" =>"http://somethingelse.com/web/stats_data2.php"
    ,"anothersomething" =>"http://anothersomething.com/web/stats_data2.php"
);

So I started to write this:

config.test = [
      something = 'http://something.com/web/stats_data2.php'
    , somethingelse = 'http://somethingelse.com/web/stats_data2.php'
    , anothersomething = 'http://anothersomething.com/web/stats_data2.php']

But I m not sure if it s not supposed to be writed like this instead:

config.test.something = 'http://something.com/web/stats_data2.php';
config.test.something = 'http://somethingelse.com/web/stats_data2.php';
config.test.anothersomething = 'http://anothersomething.com/web/stats_data2.php';

The goal is, if I do console.log(config.test.['something']);, to have the link in the output.

Is there any way to test it without server (since I don t have any before tomorrow), or is my syntax good?

  • 写回答

3条回答 默认 最新

  • doudunyi3796 2013-09-16 15:34
    关注

    Javascript does not have associative arrays, only plain objects:

    var myObj = {
        myProp: 'test',
        mySecondProp: 'tester'
    };
    
    alert(myObj['myProp']); // alerts 'test'
    
    myObj.myThirdProp = 'testing'; // still works
    
    for (var i in myObj) {
        if (!myObj.hasOwnProperty(i)) continue; // safety!
        alert(myObj[i]);
    }
    // will alert all 3 the props
    

    For converting PHP arrays to javascript use json_encode

    If you want to play it safe though, you would want to quote the properties as well, as reserved keywords will make your construct fail in some browsers, or will not be accepted by some compression systems:

    var obj1 = {
        function: 'boss',       // unsafe
        'function': 'employee'  // safe
    };
    
    console.log(obj1.function);    // unsafe
    console.log(obj1['function']); // safe
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应