我想在网站上创建一个重定向脚本,但目前没有太大成功:D
我的想法是创建一些像这样的数组:
var google = [
Google Searching,
http://www.google.com/
]
var amazon = [
Amazon Shopping
http://www.amazon.com/
]
此外,我想编写一个函数,它创建一个包含一些信息和重定向的模态框。没问题,但我不知道如何用参数调用这个数组。
例如:
gotoWebsite(google);
function gotoWebsite (website){
//search array "google" with the paramter
alert (google[0]);
alert (google[1]);
}
此示例应提醒Google Searching
和http://www.google.com/
问题:如何使用相同的命名参数调用数组?
答案 0 :(得分:0)
不确定我是否理解你的问题,但这是做什么的。首先,您的报价„
和“
可能会出现问题,如您的帖子中所示,使用"
(双引号)或'
(单引号)。
现在解决你的问题。您需要创建一个容器object()
,让它为websites
,如下所示
var websites = {};
然后将您的网站对象*放在websites
对象中,如
var websites = {
google: {
name: "Google",
url: "https://www.google.com"
},
amazon: {
name: "Amazon",
url: "https://www.amazon.com"
}
/* More objectes */
}
现在我们有一个可以使用key
的对象,但我们需要在函数内部进行包装。如果您遇到问题,可以将websites
对象移动到gotoWebsite()
范围,例如
网站未定义
function gotoWebsite(website){
console.log(websites[website]['name']); // Google
console.log(websites[website]['url']); // http://www.google.com
// OR get current key for passed parameter and assign to a variable
var website = websites[website];
console.log(website['name']); // Google
console.log(website['url']); // http://www.google.com
}
用法:
gotoWebsite('google');
// Google
// http://www.google.com
这是一个实时示例,跟踪Web Console
以查看输出
var websites = {
google: { name: "Google", url: "https://www.google.com" },
amazon: { name: "Amazon", url: "https://www.amazon.com" }
}
function gotoWebsite(website){
var website = websites[website];
console.log(website['name']);
console.log(website['url']);
}
gotoWebsite('google');
gotoWebsite('amazon');
答案 1 :(得分:0)
如果您正在寻找一种动态定义可链接网站的方法,我建议从一个数组开始,以及一个向该数组添加元素的函数:
var websites = [];
function newWebsite(name,title,url) {
websites[name] = [ title, url ];
}
然后goto函数应该有一个子句来处理试图链接尚未定义的网站:
function gotoWebsite (website){
var site = websites[website];
if (site === "array") {
alert (site[0]);
alert (site[1]);
} else {
alert ("unknown website: " + website);
}
}
网站可以从任何有权访问该功能的脚本注册:
newWebsite("google","Google Searching","http://www.google.com/");
newWebsite("amazon","Amazon Shopping","http://www.amazon.com/");
然后goto函数可以按名称获取网站
gotoWebsite("google");