這個問題在這里已經有了答案: 使用變數結果(內容)創建新變數 1 個答案 1 小時前關閉。
我有一個清單
const StudentCode = {
Jack: 32658495,
Rose: 35621548,
Lita: 63259547,
Seth: 27956431,
Cathy: 75821456,
};
如果他們的名字與另一個變數結果匹配,我該如何使用這些人的數字?
我們有
var name = *selected server-side student names*
并且通過這些 * 符號,我的意思是這是一個名字放棄的好串列,但在我們呼叫它時它只放棄了該串列中的一個名字。
如果通過name variable選擇了其中一個學生,我如何使用 const StudentCode 中該名稱前面定義的數字來生成 url?
假設你得到羅斯!那么 Rose 的號碼是:35621548,例如 url 將是https://www.35621548.com。我們可以使用什么代碼來生成這個 url,例如在控制臺中?
console.log(url)
uj5u.com熱心網友回復:
用這個:
if (StudentCode.hasOwnProperty(name){
const url = `https://www.${StudentCode[name]}.com`
}
uj5u.com熱心網友回復:
此函式將根據在此函式中傳遞的學生姓名回傳 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"));
希望這可以幫助!!
uj5u.com熱心網友回復:
const studentCode = {
Jack: 32658495,
Rose: 35621548,
Lita: 63259547,
Seth: 27956431,
Cathy: 75821456,
};
const url = 'https://$code.com'
const generateUrlForCode = function(url = '', code = '') {
return url.replace('$code', `${code}`);
}
const getCodeWithName = function(name = '') {
const code = studentCode[name];
if (!code) {
throw new Error(`There is no code with name(${name}).`);
}
return code;
}
const code = getCodeWithName('Rose'); // 35621548
const generatedUrl = generateUrlForCode(url, code); // https://35621548.com
也許它有幫助。如果代碼未創建,則會引發錯誤。請使用 try, catch 錯誤處理程式來處理錯誤。
uj5u.com熱心網友回復:
const StudentCode = {
Jack: 32658495,
Rose: 35621548,
Lita: 63259547,
Seth: 27956431,
Cathy: 75821456,
};
let studentName = "Jack"
const url = `https://${StudentCode[studentName]}.com`
console.log(url)
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/462489.html
標籤:javascript json 网址 常数 变量
下一篇:在播放器中添加隨機播放曲目的按鈕
