我有一份名单
const StudentCode = {
Jack: 32658495,
Rose: 35621548,
Lita: 63259547,
Seth: 27956431,
Cathy: 75821456,
};如果这些人的名字与另一个变量结果相匹配,我如何使用这些人的数字?
我们有
var name = *selected server-side student names*这些*符号,我的意思是,这是一个伟大的名单,名称放弃,但它只放弃了一个名字,其中的名单,在我们称为它。
如果这些学生中的一个是按name变量选择的,我如何使用在const StudentCode中该名前面定义的数字来生成url?
假设你找到萝丝了!那么Rose的数字是: 35621548,例如url将是https://www.35621548.com。例如,在控制台中,我们可以使用什么代码来生成这个url?
console.log(url)发布于 2022-04-23 12:05:04
用这个:
if (StudentCode.hasOwnProperty(name){
const url = `https://www.${StudentCode[name]}.com`
}发布于 2022-04-23 12:09:31
此函数将根据在此函数中传递的学生名称返回url。
function returnURL(studentName){
const StudentCode = {
Jack: 32658495,
Rose: 35621548,
Lita: 63259547,
Seth: 27956431,
Cathy: 75821456,
};
if (!!!StudentCode[studentName]) return "";
return "https://" + StudentCode[studentName] + ".com";
}
console.log(returnURL("Rose"));希望,这个有用!!
发布于 2022-04-23 12:23:50
export const studentUrlModule = (function() {
const studentCode = {
Jack: 32658495,
Rose: 35621548,
Lita: 63259547,
Seth: 27956431,
Cathy: 75821456,
};
const url = 'https://$code.com'
const generateUrl = function(code = '') {
if (!url) {
throw new Error('Url is not defined')
} else if (!code) {
throw new Error('Code is not defined')
};
return url.replace('$code', `${code}`);
}
function getCode(name = '') {
const code = studentCode[name];
if (!code) {
throw new Error(`There is no code with name(${name}).`);
}
return code;
}
function getUrl(name = '') {
if (!name) {
throw new Error('StudentName is undefined')
};
const code = getCode(name);
const studentUrl = generateUrl(code);
return studentUrl;
}
return {
generateUrl,
getCode,
getUrl,
};
}());也许能帮上忙。如果代码没有建立,那么它会抛出一个错误。请使用try,catch错误处理程序来处理错误。
更新我更新了代码,正如您所看到的,它是一个模块,您需要将它导入到任何您喜欢使用它的地方。
如果您不熟悉模块以及如何在浏览器中使用它们,请检查文档。
https://stackoverflow.com/questions/71979441
复制相似问题