问题描述
我在一行代码上遇到麻烦
if(words[i].endsWith(oneD[x].ending))
作品,
var thing = "oneD";
if(words[i].endsWith([thing][x].ending))
没有。 我希望他们都做同样的事情。
1楼
Tibos
2
已采纳
2015-07-25 10:57:36
可以通过两种等效的方式访问对象的属性:
obj.prop
obj['prop']
您的示例不起作用,因为那里没有对象的属性,而是变量。
解决问题的方法可能是由于在全局范围内声明的变量也显示为全局对象的属性(对于浏览器为window
):
var ans = 42;
console.log(window.ans); // 42
因此,如果oneD是全局范围内的变量,则以下两行等效:
if(words[i].endsWith(oneD[x].ending))
if(words[i].endsWith(window['oneD'][x].ending))
显然不是“oneD”你可以把它的值应该是字符串(可变文字串的thing
在你的例子)。