【问题标题】:Array of 'associative array' in (node)js(节点)js中的“关联数组”数组
【发布时间】:2013-09-16 15:30:28
【问题描述】:

我在 php 中有这段代码可以在 js 中翻译(准确地说是节点)

$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"
);

于是我开始写这个:

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']

但我不确定它是否不应该这样写:

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';

如果我执行 console.log(config.test.['something']);,目标是在输出中包含链接。

有没有办法在没有服务器的情况下测试它(因为我明天之前没有),还是我的语法好?

【问题讨论】:

标签: javascript php node.js


【解决方案1】:

Javascript 没有关联数组,只有普通对象:

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

要将 PHP 数组转换为 javascript,请使用 json_encode

如果你想安全起见,你也想引用属性,因为保留关键字会使你的构造在某些浏览器中失败,或者不会被某些压缩系统接受:

var obj1 = {
    function: 'boss',       // unsafe
    'function': 'employee'  // safe
};

console.log(obj1.function);    // unsafe
console.log(obj1['function']); // safe

【讨论】:

    【解决方案2】:

    只需使用您的配置创建一个通用对象:

    var config = {
       test: {
          something: 'http://something.com/web/stats_data2.php',
          anothersomething: 'http://anothersomething.com/web/stats_data2.php'
       }
    };
    

    那么你可以这样使用它:

    var something = config.test.something;
    

    var something = config.test['something'];
    

    var something = config['test']['something'];
    

    没有太多要测试的东西,但如果您愿意,可以使用 Firebug 或 Chrome 开发者工具等工具。

    【讨论】:

      【解决方案3】:

      使用chrome浏览器,默认打开控制台,快捷键为F12。您可以在控制台中测试您的代码。

      【讨论】:

      • 既然他在做console.log,我猜他知道这一点。
      • console.log 是node.js的一个习惯,我一般都是用它做app,而不是网页,所以console.log写在linux控制台,不是浏览器。 (而且我也从不使用 chrome 浏览器)。很高兴知道我可以在没有服务器的情况下使用 chrome 进行测试。 (即使我可能会像 letiagoalves 所说的那样使用 Firebug)。
      • console.logchrome v8 中定义,也在node.jschrome web js 中定义。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-03-07
      • 2019-07-02
      • 2018-08-23
      • 2019-10-12
      • 2019-01-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多