(node)js 中的“关联数组”数组

Array of 'associative array' in (node)js

本文关键字:数组 关联 关联数组 中的 node js      更新时间:2023-09-26

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

目标是,如果我做控制台.log(config.test.['something']);,以在输出中包含链接。

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

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

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

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开发者工具等工具。

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