我需要在Javascript中分配一个url给非常学生的名字



名单如下:

玫瑰:35621548

Jack: 32658495

Lita: 63259547

Seth: 27956431

凯蒂:75821456

假设你有一个变量作为StudentCode,包含上面的列表(我认为const将做!如:

const StudentCode = {
[Jack]: [32658495],
[Rose]: [35621548],
[Lita]: [63259547],
[Seth]: [27956431],
[Cathy]:[75821456],
};

)下面是问题:

1:我可以在URL下面定义它们吗?https://www.mylist.com/student=?StudentCode例如,Jack的链接将是:https://www.mylist.com/student=?32658495URL是虚构的。请不要点击它。

2nd:顺便说一下,整个列表超过800人,我计划保存一个外部.js文件,以便在当前代码中调用。跟我说说这个吧。万分感谢

给定

const StudentCode = {
"Jack": "32658495",
"Rose": "35621548",
"Lita": "63259547",
"Seth": "27956431",
"Cathy": "75821456",
};

你可以构造如下url:

const urls = Object.values(StudentCode).map((c) => `https://www.mylist.com?student=${c}`)
// urls: ['https://www.mylist.com?student=32658495', 'https://www.mylist.com?student=35621548', 'https://www.mylist.com?student=63259547', 'https://www.mylist.com?student=27956431', 'https://www.mylist.com?student=75821456']

要获取特定学生的url,只需执行:

const url = `https://www.mylist.com?student=${StudentCode["Jack"]}`
// url: 'https://www.mylist.com?student=32658495'

我不确定我理解你的第二个问题- 800是一个相当低的数字,所以不会有任何性能问题,如果这是你问的?

对象的属性(去掉后面的逗号之后)可以通过使用for-in循环来循环,(参见:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in)

这提供了对数组的每个键的引用,并且该键中保存的值可以使用objectName[key]引用,因此您将使用如下方式循环遍历对象:

for (key in StudentCode) { 
keyString = key; // e.g = "Jack"
keyValue = StudentCode[key]; // e.g. = 32658495
// build the urls and links
}

来构建url,字符串模板字面值将简化过程(参见:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals),允许您在字符串中替换值。例如:

url = `https://www.mylist.com/student=?${StudentCode[key]`}

注意使用反勾号和${}进行替换。

最后,要构建活动链接,创建一个元素并将其innerHTML属性设置为使用其他字符串模板文字构建的标记:

let link = `<a href=${url}>${keyValue}</a>`

这些步骤组合在下面的工作代码片段中:

const StudentCode = {
Jack: 32658495,
Rose: 35621548,
Lita: 63259547,
Seth: 27956431,
Cathy: 75821456,
};
const studentLinks = [];

for (key in StudentCode) { 
let url = `https://www.mylist.com/student=?${StudentCode[key]}`;
console.log(url);
studentLinks.push(`<a href href="url">${key}</a>`) 
}


let output= document.createElement('div');
output.innerHTML = studentLinks.join("<br>");

document.body.appendChild(output);

最新更新