我在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']);,以在输出中包含链接。
有没有办法在没有服务器的情况下测试它(因为我明天之前没有),或者我的语法是否合适?
答案 0 :(得分:4)
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
答案 1 :(得分:4)
只需使用您的配置创建一个通用对象:
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开发者工具等工具。
答案 2 :(得分:1)
使用chrome浏览器,打开控制台默认值,快捷键为 F12 。您可以在控制台中测试代码。