早上好,我有以下使用編程語言 javascript 的代碼。問題是,我被要求優化功能。減少代碼行數,也就是簡化。有什么建議嗎?謝謝
function translate(box){
var row = box.substring(1,3);
var column = box.substring(0,1);
switch(column){
case "a":
return "1" row;
case "b":
return "2" row;
case "c":
return "3" row;
case "d":
return "4" row;
case "e":
return "5" row;
case "f":
return "6" row;
case "g":
return "7" row;
case "h":
return "8" row;
}
registraMoviment(box);
}
到目前為止,我還沒有嘗試過任何事情,因為我不使用 javascript 或相關語言,但無論如何我已經得到了這個任務。謝謝
uj5u.com熱心網友回復:
您可以使用以下代碼:
const input = 'bRow';
function translate(box){
var row = box.substring(1,3);
var column = box.substring(0,1);
return (column.charCodeAt(0) - 96) row;
}
console.log(translate(input));
欲了解更多資訊,請閱讀:
- ASCII 表
- String.prototype.charCodeAt()
PS我沒有清楚地理解它的邏輯registraMoviment(box);所以我沒有在我的例子中包含它
uj5u.com熱心網友回復:
嘗試這個:
function translate(box){
var row = box.substring(1,3);
var column = box.substring(0,1);
var obj = {"a":"1", "b":"2", "c":"3", "d":"4", "e":"5", "f":"6", "g":"7", "h":"8" }
for(item in obj){
if(column === item){
return obj[item] row
}
}
registraMoviment(box);
}
uj5u.com熱心網友回復:
你可以使用你的字母的 ASCII 值來做這個更數學,但它的可讀性肯定要低得多。
function translate(box){
const row = box.substring(1,3);
const column = box.substring(0,1);
if(column >= "a" && column <= "h") {
const ASCII_VALUE_a = 97
// The 1 is to make it 1-indexed. The -ASCII_VALUE_a is to shift it so that "a" then becomes 1.
return `${column.charCodeAt() 1 - ASCII_VALUE_a}${row}`
}
registraMoviment(box);
}
const box = "b13" // expected to become "213"
console.log(translate(box)) // 213
另一個解決方案是 Justinas 的評論:
function translate(box){
const row = box.substring(1,3);
const column = box.substring(0,1);
const lookup = { a: 1, b: 2, c: 3, d: 4, e: 5, f: 6: g: 7, h: 8 }
if(column in lookup) {
return lookup[column] row
}
registraMoviment(box);
}
const box = "b13" // expected to become "213"
console.log(translate(box)) // 213
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/446498.html
標籤:javascript 优化 减少 简化
