我正在尝试为字母表中的每个字母创建一个包含两个属性的对象的数组。信和dd_array。现在我正在设置dd_array = []
,但我希望它是相应的morseDic属性。
例如_charObjArray[0] = {letter: 'a', dd_array: [0,1]}
我可以获得一些关于如何最好地编码的技巧吗?
alpha_array = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"];
morseDic = {
a: [0,1],
b: [1,0,0,0],
c: [1,0,1,0],
d: [1,0,0],
e: [0],
f: [0,0,1,0],
g: [1,1,0],
h: [0,0,0,0],
i: [0,0],
j: [0,1,1,1],
k: [1,0,1],
l: [0,1,0,0],
m: [1,1],
n: [1,0],
o: [1,1,1],
p: [0,1,1,0],
q: [1,1,0,1],
r: [0,1,0],
s: [0,0,0],
t: [1],
u: [0,0,1],
v: [0,0,0,1],
w: [0,1,1],
x: [1,0,0,1],
y: [1,0,1,1],
z: [1,1,0,0]
}
function _alpha(_char, dd_array) {
this.letter = _char;
this.dd_array = dd_array;
}
var _charObjArray = []
for (i = 0; i < alpha_array.length; i++) {
var _charNow = alpha_array[i];
var __charNow = _charNow;
var __charNow = new _alpha(_charNow, "[]") // "[]" should be replaced with the _charNow corresponding property from morseDic
_charObjArray.push(__charNow)
}
console.log(_charObjArray);
答案 0 :(得分:0)
在_alpha
中,而不是:
this.dd_array = dd_array;
...您使用_char
索引morseDic
对象:
this.dd_array = morseDic[_char];
......然后根本不要向_alpha
传递第二个参数。
但如果您希望将其作为参数传递给_alpha
:
var __charNow = new _alpha(_charNow, morseDic[_charNow]);
在JavaScript中,您可以使用点表示法和属性名称文字(obj.foo
或morseDic.a
)或使用括号表示法和属性名称 string *(obj["foo"]
或morseDic["a"]
)。在后一种情况下,字符串可以是任何表达式的结果,包括变量查找。
*在ES6中,它是字符串或Symbol
s。